让我们考虑以下使用链表实现的单读/单写队列。
struct queue {
queue() {
tail = head = &reserved;
n = 0;
}
void push(item *it) {
tail->next = it;
tail = it;
n++;
}
item* pop() {
while (n == used);
++used;
head = head->next;
return head;
}
item reserved;
item *tail, *head;
int used = 0;
std::atomic <int> n;
}
现在我发现 usingvolatile int n
可以让我的 writer 运行得更快,而我不确定它是否能保证head = head->next
总是能读取到正确的值。
更新:如果在 , 之间添加原子操作tail->next
,n++
即,
void push(item *it) {
tail->next = it;
tail = it;
a.store(0, std::memory_order_release);
a.load(std::memory_order_acquire);
n++;
}
a
读者永远不会访问哪个?这会保证 和 的顺序tail->next = it
吗head = head->next
?(不过,它比使用 atomic 运行得更快n
)