簡體   English   中英

內存屏障范圍

[英]Memory barrier scope

我不確定std::memory_order_releasestd::memory_order_acquire內存屏障的范圍是什么。 下面是一個來自cppreference的例子。 我調整了代碼來表達我的觀點:

#include <atomic>
#include <cassert>
#include <string>
#include <thread>
#include <iostream>

std::atomic<std::string*> ptr;

void producer()
{
  std::string* p  = new std::string("Hello");

  ptr.store(p, std::memory_order_release);
}

bool acquire(std::string* p2)
{
  while (!(p2 = ptr.load(std::memory_order_acquire)));

  return p2 != nullptr;
}

void consumer()
{
  std::string* p2 {nullptr};

  // while (!(p2 = ptr.load(std::memory_order_acquire))); // prints "makes sense"
  assert(acquire(p2)); // prints "what's going on?"

  if (p2 == nullptr)
  {
    std::cout << "what's going on?" << std::endl;
  }
  else
  { 
    std::cout << "makes sense" << std::endl;
  }
}

int main()
{
  std::thread t1(producer);
  std::thread t2(consumer);
  t1.join(); t2.join();
}

上面代碼的輸出是what's going on?

我熟悉(不是專家)內存障礙。 從上面的測試中,我有以下問題:

  1. std::memory_order_acquire用於acquire()函數只用於范圍acquire()根據該方案,因為在取消對輸出while(...)打印預期輸出“有道理”。 這有意義嗎? 我錯過了什么嗎?

  2. 怎么可能打印“發生了什么?”, assert(acquire(p2))清楚地表明 p2 不是nullptr ,但它以某種方式讀取if條件中的nullptr值。 我不是亂序執行規則的專家,但我希望p2 = nullptr在調用acquire()之前得到尊重, since acquire()依賴於它。

  1. acquire()函數中使用的std::memory_order_acquire用於acquire()的作用域

不。它適用於線程,不受任何函數邊界的約束。

  1. 如何打印“發生了什么?”

因為您正在修改指針的副本 改變:

bool acquire(std::string* p2)

到:

bool acquire(std::string*& p2)

使函數引用傳遞給它的同一指針。

暫無
暫無

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

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