Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you don't join your Threads?

I'm writing a ruby program that will be using threads to do some work. The work that is being done takes a non-deterministic amount of time to complete and can range anywhere from 5 to 45+ seconds. Below is a rough example of what the threading code looks like:

loop do                         # Program loop
  items = get_items
  threads = []

  for item in items
    threads << Thread.new(item) do |i|
      # do work on i
    end

    threads.each { |t| t.join } # What happens if this isn't there?
  end
end

My preference would be to skip joining the threads and not block the entire application. However I don't know what the long term implications of this are, especially because the code is run again almost immediately. Is this something that is safe to do? Or is there a better way to spawn a thread, have it do work, and clean up when it's finished, all within an infinite loop?

like image 942
Gavin Miller Avatar asked Nov 04 '10 18:11

Gavin Miller


1 Answers

I think it really depends on the content of your thread work. If, for example, your main thread needed to print "X work done", you would need to join to guarantee that you were showing the correct answer. If you have no such requirement, then you wouldn't necessarily need to join up.

like image 183
skaz Avatar answered Sep 22 '22 19:09

skaz