英文:
JRuby thread safety and arrays
问题
以下是翻译好的部分:
"JRuby关于线程安全性的官方文档"指出:
> 至少这些类不被认为是线程安全的,如果你打算与其他操作并发地对它们进行更改,你需要引入锁定(例如Mutex):String、Array、Hash以及从它们派生的任何数据结构。
这到底意味着什么,尤其是关于类本身不是线程安全的这一说法?这是否意味着如果我在一个线程中使用某个Array,而在另一个线程中使用完全不同的Array,我会遇到潜在的并发问题?还是它意味着如果我在一个线程中进行Array类的猴子补丁(monkeypatch),并在另一个线程中执行相同的操作,我可能会遇到问题?
英文:
The official document about JRuby thread safety states:
> At least these classes are not considered thread-safe, and if you intend to mutate them concurrently with other operations you will want to introduce locking (e.g. with Mutex): String, Array, Hash, and any data structures derived from them.
What exactly is the consequence of this, in particular the statement that the classes themselves are not threadsafe? Does it mean that if I use some Array in one thread, and I use a completely different Array in a different thread, I get a possible concurrency problem? Or does it mean that if I monkeypatch the Array class in one thread, and I do the same in a different thread, I could get a problem?
答案1
得分: 2
"这是否意味着,如果我在一个线程中使用某个数组,然后在不同的线程中使用完全不同的数组,会出现可能的并发问题?"
不会。
"或者是说,如果我在一个线程中对数组类进行了Monkeypatch,然后在另一个线程中也这样做,会出现问题吗?"
那将是一个问题,但这个指南不是关于Monkeypatch的。
问题在于,当一个Array
实例在多个线程之间共享时,你无法获得可预测的行为。
进一步澄清一下,如果你在一个线程中创建一个Array
,然后多个线程只是简单地读取它,那是可以的。问题出现在当一个线程对Array
实例进行变更时,而其他线程也会读取/写入同一个实例时。
对Hash
和String
也适用。"
英文:
> Does it mean that if I use some Array in one thread, and I use a completely different Array in a different thread, I get a possible concurrency problem?
No
> Or does it mean that if I monkeypatch the Array class in one thread, and I do the same in a different thread, I could get a problem?
That would be an issue but the guide is not about monkey-patching.
The problem is you can not get predictable behavior when an Array
instance is shared between multiple threads.
To clarify further if you create an Array
in one thread and than multiple threads simply read it that is okay. Issues arise when mutating an Array
instance while other threads would read/write to the same instance.
Same applies for Hash
and String
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论