c - pthread_mutex_lock 是否包含内存栅栏指令?

标签 c gcc pthreads multicore

<分区>

pthread_mutex_lockpthread_mutex_unlock 函数是否调用内存栅栏/屏障指令?还是像 compare_and_swap 隐式这样的低级指令有内存障碍?

最佳答案

Do pthread_mutex_lock and pthread_mutex_unlock functions call memory fence/barrier instructions?

他们这样做,以及创建线程。

但是请注意,有两种类型的内存屏障:编译器和硬件。

编译器屏障只阻止编译器重新排序读写和推测变量值,但不阻止 CPU 重新排序。

硬件屏障阻止 CPU 重新排序读写。全内存栅栏通常是最慢的指令,大多数时候您只需要具有获取和释放语义的操作(以实现自旋锁和互斥锁)。

对于多线程,大多数时候您都需要这两个屏障。

任何其定义在此翻译单元中不可用(并且不是固有的)的函数都是编译器内存障碍。 pthread_mutex_lockpthread_mutex_unlockpthread_create 还发出硬件内存屏障,以防止 CPU 重新排序读写。

来自 David R. Butenhof 的 Programming with POSIX Threads:

Pthreads provides a few basic rules about memory visibility. You can count on all implementations of the standard to follow these rules:

  1. Whatever memory values a thread can see when it calls pthread_create can also be seen by the new thread when it starts. Any data written to memory after the call to pthread_create may not necessarily be seen by the new thread, even if the write occurs before the thread starts.

  2. Whatever memory values a thread can see when it unlocks a mutex, either directly or by waiting on a condition variable, can also be seen by any thread that later locks the same mutex. Again, data written after the mutex is unlocked may not necessarily be seen by the thread that locks the mutex, even if the write occurs before the lock.

  3. Whatever memory values a thread can see when it terminates, either by cancellation, returning from its start function, or by calling pthread_exit, can also be seen by the thread that joins with the terminated thread bycalling pthread_join. And, of course, data written after the thread terminates may not necessarily be seen by the thread that joins, even if the write occurs before the join.

  4. Whatever memory values a thread can see when it signals or broadcasts a condition variable can also be seen by any thread that is awakened by that signal or broadcast. And, one more time, data written after the signal or broadcast may not necessarily be seen by the thread that wakes up, even if the write occurs before it awakens.

另见 C++ and Beyond 2012: Herb Sutter - atomic<> Weapons了解更多详情。

关于c - pthread_mutex_lock 是否包含内存栅栏指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24137964/

相关文章:

c - 在线程函数中获取句柄

c - C 中的 strcat 错误

段错误的原因

c++ - 模板化类特化,其中模板参数被模板化 : difference Visual Studio vs. g++

c - 为什么 pow 函数比简单操作慢?

sockets - Linux 上的最大套接字数

c - 将目标文件链接到我的项目 Eclipse CDR

c - gcc 编译器中是否有用于 pthread 代码的标志以最小化执行时间?

c - pthread_cancel() 是否有可能终止另一个意外的线程?

c++ - 如何编写代码以始终在我的程序中保持 8 个线程处于事件状态?