是否守着一个变量和Pthread互斥保证它也不会被缓存? [英] Does guarding a variable with a pthread mutex guarantee it's also not cached?
问题描述
考虑一个简单的(全球在我的情况)变量:
INT I;
某处这个变量访问
的pthread_mutex_lock(i_mutex);
如果(我==其他值){
做一点事();
}
调用pthread_mutex_unlock(i_mutex);
另一个线程更新 I
,而它持有 i_mutex
。可以在编译器缓存的值 I
等等
我不明白的最新值?必须 I
挥发?
pthread的锁执行内存屏障,这将保证缓存效果可见于其他线程。你不需要挥发性正确的共享变量处理我
如果访问共享变量由pthread的互斥体的保护。
从<一个href=\"http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11\">http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11:
下面的同步功能
内存相对于其他线程:叉()
pthread_barrier_wait()
调用pthread_cond_broadcast()
调用pthread_cond_signal()
那么pthread_cond_timedwait()
pthread_cond_wait()的
在pthread_create()
在pthread_join()
pthread_mutex_lock()的//&LT; ====
pthread_mutex_timedlock()
pthread_mutex_trylock()
调用pthread_mutex_unlock()//&LT; ====
pthread_spin_lock()
pthread_spin_trylock()
pthread_spin_unlock()
pthread_rwlock_rdlock()
pthread_rwlock_timedrdlock()
pthread_rwlock_timedwrlock()
pthread_rwlock_tryrdlock()
pthread_rwlock_trywrlock()
pthread_rwlock_unlock()
pthread_rwlock_wrlock()
sem_post()
sem_timedwait()
sem_trywait()在
sem_wait()
了semctl()
为semop()
等待()
waitpid函数()
块引用>Consider a simple (global in my case) variable:
int i;
Somewhere this variable is accessed
pthread_mutex_lock(i_mutex); if(i == other value) { do_something(); } pthread_mutex_unlock(i_mutex);
Another thread updates
i
while it holdsi_mutex
. Could the compiler cache the value ofi
so I don't get the recent value ? Musti
be volatile ?解决方案pthread locks implement memory barriers that will ensure that cache effects are made visible to other threads. You don't need volatile to properly deal with the shared variable
i
if the accesses to the shared variable are protected by pthread mutexes.from http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11:
The following functions synchronize memory with respect to other threads:
fork() pthread_barrier_wait() pthread_cond_broadcast() pthread_cond_signal() pthread_cond_timedwait() pthread_cond_wait() pthread_create() pthread_join() pthread_mutex_lock() // <==== pthread_mutex_timedlock() pthread_mutex_trylock() pthread_mutex_unlock() // <==== pthread_spin_lock() pthread_spin_trylock() pthread_spin_unlock() pthread_rwlock_rdlock() pthread_rwlock_timedrdlock() pthread_rwlock_timedwrlock() pthread_rwlock_tryrdlock() pthread_rwlock_trywrlock() pthread_rwlock_unlock() pthread_rwlock_wrlock() sem_post() sem_timedwait() sem_trywait() sem_wait() semctl() semop() wait() waitpid()
这篇关于是否守着一个变量和Pthread互斥保证它也不会被缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!