默认情况下,Ruby Thread-Safe是否安全? [英] Is Ruby Thread-Safe by default?

查看:76
本文介绍了默认情况下,Ruby Thread-Safe是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制台中运行以下代码10次以上,结果是相同的输出100000.

I ran following code in console for more than 10 times, and it resulted in same output, 100000.

i = 0
1000.times do
Thread.start { 100.times { i += 1 } }
end
i

它不应该为我提供不同的输出,因为我正在使用多个线程读取和更新i.这让我感到奇怪,默认情况下,ruby是否真的是线程安全的?如果不是,那么为什么我总是看到相同的输出?

Shouldn't it give me different output, as I'm reading and updating i, using multiple threads. It made me wonder, is ruby actually thread-safe by default? If not, then why do I see same output always?

p.s.如果您说的话,默认情况下它不是线程安全的,那么您可以分享一个简单的示例,当我在Rails控制台中运行时,会给我带来不同的结果吗?

p.s. If you say, it is not thread-safe by default then can you share a simple example, which will give me different result when I run in rails console?

换句话说,以上代码是否同时运行1000个线程?如果是,则结果不应为100000 始终.如果否,那么如何同时运行多个线程?

In other words, is above code running 1000 threads concurrently? If yes, then result shouldn't be 100000 ALWAYS. If no, then how to run multiple threads concurrently?

如果添加puts,则i的打印顺序将改变.这意味着线程彼此交错,但是它们是否同时运行?

If I add puts, then print order of i will change. It implies threads are interleaving each other, but are they running concurrently?

我不是在问如何使此线程安全.我了解mutex/locking&同步/异步过程.因为我理解它们,所以我无法理解这段代码的输出.

I'm not asking, how to make this thread-safe. I understand concepts of mutex/locking & synchronous/asynchronous process. Because I understand them, I'm failing to understand output of this code.

推荐答案

呵呵!最终,我找到了一种方法来证明,它不会总是在irb上导致100000.

Huh!! Finally I found a way to prove, that it will not result 100000 always on irb.

运行下面的代码给了我这个主意,

Running following code gave me the idea,

100.times do
i = 0
1000.times do
Thread.start { 100.times { i += 1 } }
end
puts i
end

在大多数情况下,我看到不同的值.通常,它的范围是91k to 100000.

I see different values, most of the times. Mostly, it ranges from 91k to 100000.

这篇关于默认情况下,Ruby Thread-Safe是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆