为什么螺纹#杀死防止在Ruby中创建新线程并默默失败?

发布于 2025-02-11 20:28:54 字数 394 浏览 1 评论 0原文

杀死线程后,创建新线程似乎会默默失败。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丑丑阿 2025-02-18 20:28:54

最后一个线程默默失败。

您正在得出错误的结论,这是线程没有产生输出。如果您打印不同的值:

thread = Thread.new { sleep 1; puts 'ok #1' }
sleep 2
thread = Thread.new { sleep 1; puts 'ok #2' }
sleep 2

puts "-----"

thread = Thread.new { sleep 1; puts 'ok #3' }
thread.kill
thread = Thread.new { sleep 1; puts 'ok #4' }
sleep 2

输出:

ok #1
ok #2
-----
ok #4

如何杀死线程并创建新线程?

您确实做到了。倒数第二个线程实例在睡觉时通过thread.kill被杀死(也许之前)。最后一个线程实例照常工作。您的代码没有失败。

Last thread fails silently.

You're drawing the wrong conclusion, it's the thread before that doesn't generate output. It becomes obvious if you print different values:

thread = Thread.new { sleep 1; puts 'ok #1' }
sleep 2
thread = Thread.new { sleep 1; puts 'ok #2' }
sleep 2

puts "-----"

thread = Thread.new { sleep 1; puts 'ok #3' }
thread.kill
thread = Thread.new { sleep 1; puts 'ok #4' }
sleep 2

Output:

ok #1
ok #2
-----
ok #4

How to kill a thread and create a new one?

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文