简体   繁体   English

C ++ pthread,两个线程读取一个全局变量

[英]C++ pthread, two threads read a global variable

如果有两个线程只读取全局变量,是否有必要使用互斥锁来锁定和解锁全局变量?

If the threads are only reading the variable and nobody is writing to it (not one of the threads, not someone else), then you're perfectly fine without locks. 如果线程只读取变量并且没有人写入它(不是其中一个线程,而不是其他人),那么没有锁定你就完全没问题了。 If any concurrent modification could happen, then everyone (including pure readers) must be synchronised somehow - by a mutex, a read/write lock or in some other way. 如果可能发生任何并发修改,那么每个人(包括纯读者)必须以某种方式同步 - 通过互斥锁,读/写锁或其他方式。

In general, exclusive access is required to prevent one from seeing an inconsistent state . 通常,需要独占访问以防止看到不一致的状态 For a reader thread, this means avoiding partial reads . 对于读者线程,这意味着避免部分读取

What does that mean ? 那是什么意思 ? Imagine that you have a value stored on two (atomic) integers, for example coordinates. 想象一下,你有一个存储在两个(原子)整数上的值,例如坐标。

int i = 3;
int j = 4;

Now, we are going to read i and j whilst they undergo modification, more precisely when a Writer thread want to move in a diagonal fashion from (3, 4) to (4, 5) : 现在,我们将在进行修改时阅读ij ,更确切地说,当Writer线程想要以对角线方式从(3, 4)(4, 5)

Reader     Writer
  |          |
  |        i = 4
  |          |
i = 4     <pause>
j = 4        |
  |        j = 5
  |          |

This is called a partial read : the Reader thread has gotten information that the object is at (4, 4) even though it was never there . 这称为部分读取Reader线程已获得对象所在的信息(4, 4)即使它从未出现过 I'll let you think what occurs if those coordinates are used to compute the trajectory of a plane... 我会让你想一想,如果这些坐标用于计算飞机的轨迹,会发生什么......

Avoiding partial reads however is fairly easy: mutations should be seen atomically. 然而,避免部分读取相当容易:应该原子地看到突变。

  • if there is no mutation (for the duration of the reads) then you can just read 如果没有突变(读取的持续时间),那么你可以阅读
  • if there are mutations, you need a mutual exclusion mechanism (such as a reader/writer mutex) 如果有突变,则需要互斥机制(如读写器互斥)

And thus, to answer your question, if the only accesses are read accesses, the no synchronization is required. 因此,要回答您的问题,如果只有访问是读访问,则不需要同步。 But if you sometimes (even infrequently) modify the information read, then you need some mechanism. 但是,如果您有时(甚至不经常)修改读取的信息,那么您需要一些机制。

如果他们只是阅读,那么你不需要锁定。

If they are just reading then no need of lock but when that is not the case then I think mutex will ensure that reading thread will not eat resources while it has nothing to do. 如果他们只是阅读然后不需要锁定,但是当不是这种情况时,我认为互斥将确保阅读线程不会占用资源,而它无关紧要。

Something like this:- 像这样: -

Thread1() {
Mutex_lock();
Process global_variable;
Unlock_mutex();
}

Similarly for Thread2 类似于Thread2

On a side note:- 在旁注: -

Mutex is generally used to prevent multiple threads from accessing shared memory or other resources concurrently. Mutex通常用于防止多个线程同时访问共享内存或其他资源。 Also to remember that it does not lock anything by itself 还要记住,它本身并没有锁定任何东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM