我正在使用原子(双)比较和交换指令实现无锁机制,例如cmpxchg16b
我目前正在汇编中编写它,然后将其链接进去.但是,我想知道是否有办法让编译器自动为我执行此操作?例如,带有'原子级'的环绕代码块,并让它弄清楚如何将代码实现为底层处理器体系结构中的原子指令(或者如果底层arch不支持它,则在编译时生成错误)?
PS我知道gcc有一些内置函数(至少对于CAS)
http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html#Atomic-Builtins
假设我有一个程序初始化一个全局变量供线程使用,如下所示:
int ThreadParameter;
// this function runs from the main thread
void SomeFunction() {
ThreadParameter = 5;
StartThread(); // some function to start a thread
// at this point, ThreadParameter is NEVER modified.
}
// this function is run in a background worker thread created by StartThread();
void WorkerThread() {
PrintValue(ThreadParameter); // we expect this to print "5"
}
Run Code Online (Sandbox Code Playgroud)
这些问题应适用于可能遇到的任何通用处理器体系结构.我希望解决方案是可移植的 - 不是特定于具有更强内存保证的架构,如x86.
volatile; 是否可能会在StartThread()通话结束后重新订购并留下我的话?如何解决这个问题?ThreadParameter程序开始运行之前,包含的内存块已被分页到每个处理器的缓存中SomeFunction(). SomeFunction()写5来ThreadParameter …