并行编程中,我们需要确保在并发访问内存时,不会出现数据竞争或数据不一致的情况。READ_ONCE和WRITE_ONCE是用来保证内存读写操作完成且不被中断的宏定义。
下面是包含READ_ONCE和WRITE_ONCE的示例代码:
#include
#define READ_ONCE(x) {
typeof(x) __val = *(volatile typeof(x) *)&(x);
(void)__val;
}
#define WRITE_ONCE(x, val) do {
*(volatile typeof(x) *)&(x) = (val);
} while (0)
int x = 0;
void *thread_func(void *arg) { for (int i = 0; i < 1000000; ++i) { WRITE_ONCE(x, i); } pthread_exit(NULL); }
int main() { pthread_t t1, t2; pthread_create(&t1, NULL, thread_func, NULL); pthread_create(&t2, NULL, thread_func, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); READ_ONCE(x); printf("x = %d\n", x); return 0; }
在上面的示例中,使用WRITE_ONCE写入变量x,两个线程同时执行。使用READ_ONCE读取x的值,确保在所有线程执行完毕后读取到的值是正确的。