为什么螺纹#杀死防止在Ruby中创建新线程并默默失败?
杀死线程后,创建新线程似乎会默默失败。
thread = Thread.new { sleep 1; puts :ok }
sleep 2
thread = Thread.new { sleep 1; puts :ok }
sleep 2
puts "#2"
thread = Thread.new { sleep 1; puts :ok }
thread.kill
thread = Thread.new { sleep 1; puts :ok }
sleep 2
输出:
ok
ok
#2
ok
最后一个线程默默失败。
如何杀死线程并创建新线程?
在Ruby 2.6.8p205和Ruby 3.1.0p0上测试
After killing a thread, creating new threads seems to fail silently.
thread = Thread.new { sleep 1; puts :ok }
sleep 2
thread = Thread.new { sleep 1; puts :ok }
sleep 2
puts "#2"
thread = Thread.new { sleep 1; puts :ok }
thread.kill
thread = Thread.new { sleep 1; puts :ok }
sleep 2
Output:
ok
ok
#2
ok
Last thread fails silently.
How to kill a thread and create a new one?
Tested on ruby 2.6.8p205 and ruby 3.1.0p0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在得出错误的结论,这是线程没有产生输出。如果您打印不同的值:
输出:
您确实做到了。倒数第二个线程实例在睡觉时通过
thread.kill
被杀死(也许之前)。最后一个线程实例照常工作。您的代码没有失败。You're drawing the wrong conclusion, it's the thread before that doesn't generate output. It becomes obvious if you print different values:
Output:
You exactly did that. The penultimate thread instance gets killed via
thread.kill
while it is sleeping (maybe even before). The last thread instance works as usual. There's no failure in your code.