10

次のコード標準は準拠していますか? x(または、アトミックにせずに準拠させることはできますかvolatile?)

これは以前の質問に似ていますが、C++ 標準の関連セクションへの引用をお願いします。

私の懸念は、アトミックstore()でありload()、非アトミック変数 (x以下の例) が正しい解放および取得セマンティクスを持つための十分なコンパイラ バリアを提供していないことです。

私の目標は、スレッド間で通常の C++ データ構造へのポインターを転送できる、キューなどのロックフリーのプリミティブを実装することです。

#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>

int x; // regular variable, could be a complex data structure

std::atomic<int> flag { 0 };

void writer_thread() {
    x = 42;
    // release value x to reader thread
    flag.store(1, std::memory_order_release);
}

bool poll() {
    return (flag.load(std::memory_order_acquire) == 1);
}

int main() {
    x = 0;

    std::thread t(writer_thread);

    // "reader thread" ...  
    // sleep-wait is just for the test.
    // production code calls poll() at specific points

    while (!poll())
      std::this_thread::sleep_for(std::chrono::milliseconds(50));

    std::cout << x << std::endl;

    t.join();
}
4

1 に答える 1