ruby - Thread#run 和 Thread#wakeup 之间的区别?

标签 ruby multithreading

在 Ruby 中,Thread#runThread#wakup 有什么区别?

RDoc 指定 scheduler 不使用 Thread#wakeup 调用,但这是什么意思?何时使用唤醒运行 的示例?谢谢。

编辑:
我看到 Thread#wakup 导致线程变为可运行状态,但如果在执行 Thread#run 之前它不会执行(无论如何都会唤醒线程),它有什么用?

有人可以提供一个示例,其中wakeup 做了一些有意义的事情吗?出于好奇 =)

最佳答案

这里有一个例子来说明它的含义(来自 here 的代码示例):

线程唤醒

thread = Thread.new do 
  Thread.stop
  puts "Inside the thread block"
end

$ thread
=> #<Thread:0x100394008 sleep> 

以上输出表示新创建的线程因为停止命令而处于休眠状态。

$ thread.wakeup
=> #<Thread:0x100394008 run>

此输出表明线程不再休眠,可以运行。

$ thread.run
Inside the thread block
=> #<Thread:0x1005d9930 sleep>   

现在线程继续执行并打印出字符串。

$ thread.run
ThreadError: killed thread

线程运行

thread = Thread.new do 
  Thread.stop
  puts "Inside the thread block"
end

$ thread
=> #<Thread:0x100394008 sleep> 

$ thread.run
Inside the thread block
=> #<Thread:0x1005d9930 sleep>   

线程不仅被唤醒而且继续执行并打印出字符串。

$ thread.run
ThreadError: killed thread

关于ruby - Thread#run 和 Thread#wakeup 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12763593/

相关文章:

ruby-on-rails - Ruby on Rails : Multiple Input Fields in The Same Form - Change ID/Value

ruby-on-rails - Rails after_save 和 after_commit 回调

ruby - 何时在 Ruby 方法中使用 `self.foo` 而不是 `foo`

c# - 以原子方式从 ConcurrentQueue 中获取所有内容

c# - 具有 SQL Server 数据库调用的多线程 C# 应用程序

java - 具有变化对象的连续线程

java - 尝试等待所有线程完成

ruby - 为什么分配变量时 do/end block 的行为/返回不同?

ruby - sinatra 中的嵌套布局

java - 线程局部变量