Thread.join blocks the main thread

后端 未结 2 1070
别跟我提以往
别跟我提以往 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: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
    

提交回复
热议问题