锁定访问共享内存进行读取时 [英] Locking when accessing shared memory for reading

查看:155
本文介绍了锁定访问共享内存进行读取时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我访问共享内存为只读,来检查条件的如果()块,我应该还是锁定互斥?例如。

If I am accessing shared memory for reading only, to check a condition for an if() block, should I still lock the mutex? E.g.

mutex_lock();

if (var /* shared memory */) {

}

mutex_unlock();

时锁需要在这里和好的做法呢?

Is locking here needed and good practice?

推荐答案

如果您正在阅读的变量可以被写入并行,那么,你应该获得互斥锁。

If the variable you are reading could be written to concurrently, then yes, you should acquire a lock on the mutex.

如果你的编译器为您提供了必要的原语你只能读它原子;这可以是附带C11和C ++ 11或你的编译器提供了一些其他语言的扩展原子的特性。然后,你可以互斥收购进入条件,但如果等到测试后获取互斥锁,那么别人可能会改变它的时候你们之间测试它的时候,你获得互斥:

You could only read it atomically if your compiler provides you with the necessary primitives for that; this could be either the atomic features that come with C11 and C++11 or some other language extension provided by your compiler. Then you could move the mutex acquisition into the conditional, but if you wait until after the test to acquire the mutex then someone else may change it between the time you test it and the time you acquire the mutex:

if (example) {
    // "example" variable could be changed here by another thread.

    mutex_lock();

    // Now the condition might be false!

    mutex_unlock();
}

因此​​,我建议之前,有条件获取互斥体,除非分析精确定位了收购互斥的瓶颈。 (而在测试变量大于CPU寄存器大的情况下 - 在32位CPU上的64位数字,例如 - 那么你甚至不必拖延收购互斥的选择没有一些其他类型原子取或比较原始的。)

Therefore, I would suggest acquiring the mutex before the conditional, unless profiling has pinpointed mutex acquisition as a bottleneck. (And in the case where the tested variable is larger than a CPU register -- a 64-bit number on a 32-bit CPU, for example -- then you don't even have the option of delaying mutex acquisition without some other kind of atomic fetch or compare primitive.)

这篇关于锁定访问共享内存进行读取时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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