Thread.join blocks the main thread

后端 未结 2 1050
别跟我提以往
别跟我提以往 2020-12-24 14:24

Calling Thread.join blocks the current (main) thread. However not calling join results in all spawned threads to be killed when the main thread exits. How does one spawn per

相关标签:
2条回答
  • 2020-12-24 15:01

    You simply accumulate the threads in another container, then join them one-by-one after they've all been created:

    my_threads = []
    for i in 1..100 do
        puts "Creating thread #{i}"
        my_threads << Thread.new(i) do |j|
            sleep 1
            puts "Thread #{j} done"
        end
    end
    puts "#{Thread.list.size} threads"
    
    my_threads.each do |t|
        t.join
    end
    

    You also can't bind the thread to the i variable because i gets constantly overwritten, and your output will be 100 lines of "Thread 100 done"; instead, you have to bind it to a copy of i, which I have cleverly named j.

    0 讨论(0)
  • 2020-12-24 15:10

    You need to join the threads outside of the loop.

    for i in 1..100 do
      puts "Creating thread #{i}"
      t = Thread.new(i) do |mi|
        sleep 1
        puts "Thread #{mi} done"
      end
    end
    
    # Wait for all threads to end
    Thread.list.each do |t|
      # Wait for the thread to finish if it isn't this thread (i.e. the main thread).
      t.join if t != Thread.current
     end
    
    0 讨论(0)
提交回复
热议问题