在哪些情况下需要锁定变量以防止同时访问? [英] in which cases do I need to lock a variable from simultaneous access?

查看:118
本文介绍了在哪些情况下需要锁定变量以防止同时访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C或C ++程序中,如果2个线程使用相同的全局变量,则需要通过互斥锁来锁定var.

In a C or C++ program, if 2 threads use the same global variable, then you need to lock the var via a mutex.

但是在哪种情况下呢?

  1. 线程1:读取线程2:读取
  2. 线程1:写入线程2:读取
  3. 线程1:写入线程2:写入

您当然需要锁定第3种情况,但其他2种情况又如何呢?情况2(使用非原子操作)会发生什么?是否存在某种访问冲突,或者线程2只是获得了旧值?我对此感到困惑,因为无法同时访问(在普通PC硬件中)硬件级别的内存和寄存器,还是我们有某种并行CPU,这些CPU带有并行总线到并行ram芯片?

Of course you need to lock at case 3 but what is with the other 2 cases? What happens at case 2 (with non atomic operations)? Is there some kind of access violation or does Thread 2 just get the old value? I'm a litle confused about this, because memory and registers on the hardware level can't be accessed at the same time (in normal PC hardware) or do we have some kind of parallel CPUs with parallel bus lines to parallel ram chips?

推荐答案

仅考虑每种情况下可能发生的情况.让我们只考虑比赛条件:这很容易,而且足以让我们看到后果.

Just think of what may happen in each of the cases. Let's only consider the race condition: it's easy and it's enough for us to see the consequences.

在情况1中,变量没有被修改,因此无论顺序如何,两个线程将读取相同的值.因此,基本上,这里没有错.

In case 1, the variable is not being modified, so no matter which the order is, both threads will read the same value. So basically, nothing is wrong here.

情况2和3更糟.假设您有一个竞争条件,并且不知道哪个线程可以更早地访问.这意味着:

Cases 2 and 3 are worse. Let's say you have a race condition, and don't know which of the threads will get access earlier. That means:

对于情况2:在所有操作结束时,变量的值都很好(它将是线程1写入的值),但是线程2可能会获得该变量的旧值,这可能会导致崩溃,或其他问题.

For case 2: The value of the variable in the end of all operations is fine (it will be the value written by Thread 1), but Thread 2 may get an old value of the variable, which may cause a crash, or other problems.

对于情况3:变量的最终值是不可预测的,因为它取决于最后执行写操作的线程.

For case 3: The end value of the variable is not predictable, since it depends on which thread will perform the write operation last.

对于情况2和3,还可能发生一种情况:当线程处于不一致状态时,其中一个线程将尝试访问该变量,并且最终可能会导致其中一个线程读取了一些垃圾数据(例如Case 2),甚至在完成所有操作后,将变量中的垃圾数据清除.

For cases 2 and 3, it may also happen that one of the threads will try to access the variable while it is in an inconsistent state, and you may end up with some rubbish data read by one of the threads (i.e. Case 2), or even rubbish data in the variable after completion of all operations.

是的,请锁定情况2和3.

So yea, lock for cases 2 and 3.

这篇关于在哪些情况下需要锁定变量以防止同时访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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