簡體   English   中英

c++ - 如何確保多線程分別在兩個無鎖隊列上推送兩個值(在一個原子操作中)而不使用 C++ 中的鎖?

[英]How to ensure multi-threads push two values on two lockfree queues respectively (in one atomic operation) without using lock in C++?

我試圖找出一種方法將兩個值推送到兩個 boost::lockfree::queues 並保留這對值的序列。 尋求一些想法。

例如,我的輸入值為 {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

我試圖刪除鎖的原因是因為另一個線程也在使用鎖,所以我的代碼達到了deallock。 我有一個復雜的設計,涉及 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_order_acq_rel。 此解決方案是無鎖的,但不是無等待的。

顯然,根據文章,這可能是一個糟糕的解決方案: 將鎖與自旋鎖進行比較https://matklad.github.io/2020/01/04/mutexes-are-faster-than-spinlocks.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM