Can ruby ​​generate non-daemon threads?

For Python, a non-mononic stream can be created by setting the property daemon

. Below is the introduction daemon

:

A Boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before calling start (), otherwise the RuntimeError will be raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created on the main thread are daemon = False by default.

The entire Python program exits when there is no living non-daemon left.

https://docs.python.org/2/library/threading.html#threading.Thread.daemon gives more details.

I know Python and Ruby have a method join()

to wait for a thread to complete. Also, in the following code snippet, the program terminates when the thread ends a

.

#!/usr/bin/env ruby
# coding: UTF-8

a = Thread.new() do
    1000.times do |value|
        puts "---" + value.to_s
    end
end

while a.status != false 
    # do something
end
puts 'I am the main thread'

      

Can Ruby generate non-mononic streams exactly like Python?

+3


source to share


1 answer


Ruby Themes demonstrate Python's daemonic behavior by default, but don't really have such a built-in concept.

Your example, without while

(or join

/ value

), will exit when the main program reaches the end.



For threads to accept non-daemonic Python behavior, you need to specifically wait for them.

require 'thwait' #stdlib

wait_threads = []

wait_threads.push( Thread.new() do
  1000.times do |value|
    printf "%s ", value
  end
end )

Thread.new() do
  sleep 1
  puts "I am like a python daemon"
end

ThreadsWait.all_waits( *wait_threads )
puts 'I am the main thread'

      

+3


source







All Articles