2015-08-16 91 views
0

比方說,我是一個線程中:從另一個線程執行ruby的主線程上的代碼?

Thread.new do 
    #something 
end 

而且我們說,「東西」是不是線程安全的,需要在主線程上運行。

在Ruby中有沒有任何方式來調度要在主線程上執行的代碼?

+4

請看http://stackoverflow.com/questions/10045693/how-與線程在紅寶石和http://stackoverflow.com/questions/3208462/does-ruby-have-the-java-equivalent-of-synchronize-keyword –

回答

0

你可以使用一個隊列發送PROC的主線程,然後從主線程這樣稱呼他們:

command_queue = Queue.new 

# Child thread 
Thread.new do 
    sleep 1 

    command_queue << proc { puts "1" } 

    sleep 1 

    command_queue << proc { puts "2" } 

    sleep 1 

    command_queue << proc { exit } 
end 

# Main thread 
while command = command_queue.pop 
    command.call 
end 
相關問題