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

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

问题描述

如果我正在访问共享内存以供读取,为检查 if()块的条件,是否仍应锁定互斥体?例如

  mutex_lock(); 

if(var / * shared memory * /){

}

mutex_unlock();

这里是否需要锁定和良好实践?

解决方案

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



如果你的编译器为你提供了必要的原语,你只能原子地读它;这可能是C11和C ++ 11附带的原子特性或编译器提供的其他语言扩展。然后你可以将互斥锁移动到条件中,但如果你等到测试之后获取互斥锁,那么其他人可能会在你测试它和获取互斥锁的时间之间改变它:

  if(example){
//example变量可以在这里被另一个线程改变。

mutex_lock();

//现在条件可能是false!

mutex_unlock();因此,我建议在条件之前获取互斥体,除非分析已精确定位。互斥获取作为瓶颈。 (在被测变量大于CPU寄存器(例如32位CPU上的64位数)的情况下,您甚至不能选择延迟互斥量获取而不使用其他类型的原子获取或比较原语。)


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.

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();
}

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天全站免登陆