[英]C/C++ shared memory, atomic operations, Linux
I'm doing inter-process communication using shared memory on a multi- processor server. 我正在使用多处理器服务器上的共享内存进行进程间通信。 I've simplified the code to the following:
我将代码简化为以下内容:
struct MyStruct {
uint64_t x;
};
volatile MyStruct* my_struct; // initialized elsewhere
void MyFunction(uint64_t y) {
while (true) {
uint64_t current_x = my_struct->x;
if (__sync_bool_compare_and_swap(&my_struct->x, current_x, y)) {
DoWork(current_x, y); // do work here depending on current_x and y
return;
}
}
}
My question: is this code correct? 我的问题:此代码正确吗?
In particular, do I need to add a 特别是我需要添加一个
__sync_synchronize()
before the line 行前
uint64_t current_x = my_struct->x
or will that be redundant since the atomic CAS on the following line effectively does that anyways? uint64_t current_x = my_struct->x
还是多余的,因为下一行的原子CAS仍然有效吗? As you can see, what effectively I want is the __sync_lock_test_and_set functionality. 如您所见,我真正想要的是__sync_lock_test_and_set功能。 However, from http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html it looks like that function may not work always as expected.
但是,从http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html看来,该功能可能无法始终按预期运行。
while (true) {
uint64_t current_x = my_struct->x;
/* CAVEAT: my_struct may point to something different now */
if (__sync_bool_compare_and_swap(&my_struct->x, current_x, y)) {
If you don't care that my_struct
may point to a different structure, but has the same x
value as the original struct, then the code seems fine. 如果您不关心
my_struct
可能指向不同的结构,但是具有与原始结构相同的x
值,则该代码看起来不错。 It seems your code implies that it is okay, because your DoWork
only cares about current_x
and y
. 看来您的代码暗示这样做还可以,因为您的
DoWork
只关心current_x
和y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.