在论文“实时和非实时应用程序之间的非阻塞同步”中,清单 2 中收听了以下伪代码。它建议为单个实时编写器和一个或多个非阻塞实现-实时阅读器。
volatile counter : pointer to shared memory area of an integer
data_size : unsigned
pt_base : pointer to shared memory area of data_size bytes
initialization (d_size: unsigned)
counter := 0
data_size := d_size
pt_base := allocate data_size bytes in the shared memory
//Real-time operation
write (new_value: pointer)
local_counter := *counter
*counter := local_counter + 1
copy data_size bytes from *new_value
*pt_base*data_size
*counter := local_counter + 2
//Non-real-time operation
read (pt_data: pointer)
loop
counter_begin := *counter
copy data_size bytes from *pt_base to *pt_data *data_size
counter_end := *counter
if (counter_end == counter_begin and counter_begin is even)
break;
endif
endloop
如何使用 C11 _Atomic、gcc/clang __atomic 或仅使用易失性和内存屏障(如果可能的话)在 C 中正确实现?
在他对另一个问题的回答Peter Cordes暗示volatile和内存屏障可能就足够了,或者至少我是这样理解的。