是否有必要锁定一个*仅从一个线程写入*而*仅从另一个线程读取的数组?
我有两个线程正在运行.他们共享一个数组.其中一个线程向数组添加新元素(并删除它们),另一个线程使用该数组(仅限读取操作).在添加/删除数组或从中读取数组之前,我是否需要锁定数组?
I have two threads running. They share an array. One of the threads adds new elements to the array (and removes them) and the other uses this array (read operations only). Is it necessary for me to lock the array before I add/remove to/from it or read from it?
更多细节:
- 我需要在另一个线程中不断迭代整个数组.没有前面提到的写操作.只需扫描固定大小的循环缓冲区之类的东西"
- 在这种情况下,最简单的方法是使用锁.然而,锁可能会很慢.如果可以避免使用锁,我不想使用它们.此外,正如从讨论中得出的那样,可能没有必要(实际上没有必要)锁定阵列上的所有操作.只需锁定数组的迭代器管理(其他线程将使用的计数变量)就足够了
我不认为这个问题太宽泛了".如果结果仍然如此,请告诉我.我知道这个问题并不完美.我必须结合至少 3 个答案才能解决这个问题——这表明大多数人无法完全理解所有问题,被迫做一些猜测工作.但其中大部分是通过我试图纳入问题的评论得出的.这些答案帮助我非常客观地解决了我的问题,我认为这里提供的答案对于刚开始使用多线程的人来说是非常有用的资源.
I don't think the question is "too broad". If it still comes out to be so, please let me know. I know the question isn't perfect. I had to combine at least 3 answers in order to be able to solve the question - which suggests most people were not able to fully understand all the issues and were forced to do some guess work. But most of it came out through the comments which I have tried to incorporate in the question. The answers helped me solve my problem quite objectively and I think the answers provided here are quite a helpful resource for someone starting out with multithreading.
如果两个线程在同一个内存位置执行一个操作,并且至少有一个操作是写操作,你就有所谓的数据竞争.根据 C11 和 C++11,具有数据竞争的程序的行为是未定义的.
If two threads perform an operation on the same memory location, and at least one operation is a write operation, you have a so-called data race. According to C11 and C++11, the behaviour of programs with data races is undefined.
所以,你必须使用某种同步机制,例如:
So, you have to use some kind of synchronization mechanism, for example: