如何确保多线程在C++中不使用锁的情况下(在一个原子操作中)分别在两个无锁队列上推送两个值



我正试图找到一种方法,将两个值推送到两个boost::lockfree::队列中,并保留这对值的序列。寻求一些想法。

例如,我的输入值是{apple1,apple2},{orange1,orange2},{peach1,peach2}。。。两个队列应该看起来像:

Q1: apple1, orange1, peach1, ...
Q2: apple2, orange2, peach2, ...
/// multithreads can execute the following code
lockfree::queue<string*> q1(100), q2(100);
string* val1 = new String("first");
string* val2 = new String("second");
unique_lock<mutex> lk(mtx);
while (!q1.push(val1)); while (!q2.push(val2));
lk.unlock();
// do some more things

我试图移除锁的原因是因为我的代码正在达到解除锁,因为另一个线程也在使用锁。我有一个复杂的设计,需要10多个线程协同完成一项任务。

最后我发现了如何用循环替换锁。在我的设计中,这似乎提高了性能。

atomic<bool> qguard(false);
while (true) {
bool canpush=false;
if (qguard.compare_exchange_strong(canpush, true)) {
while (!q1.push(val1));
while (!q2.push(val2));
qguard.store(false);
break;
}
}

我认为这可以进一步提高1。使用atomic_flag。2.在compare_exchange_strong((函数和memory_order_release中使用memory_orderAcq_rel。此解决方案是无锁定的,但不是无等待的。

显然,根据这篇文章,这可能是一个糟糕的解决方案:将锁与旋转锁进行比较https://matklad.github.io/2020/01/04/mutexes-are-faster-than-spinlocks.html

最新更新