c++ - 在一个线程中完成的操作对另一个线程可见,而无需显式同步

标签 c++ multithreading asynchronous language-lawyer

我的问题是关于线程同步的。请参见下面的代码:

std::vector<int> v_int;

for (size_t i = 0; i < 5; ++i) {
    v_int.emplace_back(i);
}

auto f_async = std::async(std::launch::async,
    [](auto v_int) mutable {
        for (auto& el : v_int.get()) {
            el += 10;
        }
    }, std::ref(v_int));

//more instructions...

f_async.get();
我的问题是鉴于没有获取释放(互斥体,原子 bool ,原子标志...),std::async产生的新线程如何“看到”(主)线程对 vector 所做的修改。 )来保护 vector ?
给定新线程在完全写入 vector 后“发生”的情况下,是否存在隐式顺序一致性?
一个典型的生产者/消费者看起来像这样:
std::vector<int> v_int_global;
std::atomic<bool> data_ready{ false };

void producer_int() {
    for (size_t i = 0; i < 5; ++i) {
        v_int_global.emplace_back(i);
    }
    data_ready.store(true, std::memory_order_release);
}

void transformer_int() {
    while (!data_ready.load(std::memory_order_acquire));
    for (auto& el : v_int_global) {
        el += 10;
    }
}

int main() {
    std::thread t1 (producer_int);
    std::thread t2 (transformer_int);

    t1.join();
    t2.join();
}
谢谢你。

最佳答案

std::async被指定为与参数([futures.async]/p5)的调用同步:

Synchronization: Regardless of the provided policy argument,

(5.1) the invocation of async synchronizes with the invocation of f. [ Note: This statement applies even when the corresponding future object is moved to another thread.  — end note ] ; and

(5.2) the completion of the function f is sequenced before ([intro.multithread]) the shared state is made ready. [ Note: f might not be called at all, so its completion might never happen.  — end note ]


术语“与...同步”表示将发生至少一个“获取释放”事件。因此,保证在调用std::async之前完成的任何工作对于lambda都是可见的,而不管它何时执行。
同样,future::get()与以共享状态([futures.state]/p9)存储结果的调用同步:

Calls to functions that successfully set the stored result of a shared state synchronize with calls to functions successfully detecting the ready state resulting from that setting. The storage of the result (whether normal or exceptional) into the shared state synchronizes with the successful return from a call to a waiting function on the shared state.

关于c++ - 在一个线程中完成的操作对另一个线程可见,而无需显式同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63602431/

相关文章:

java - 使用 websockets 的多线程

c# - 在 ASP.Net Core 应用程序启动期间运行异步代码

javascript - 在 Javascript 异步函数之外访问 JSON 数组元素

python - 了解tornado协程装饰器+twitter认证

c++ - Arduino SoftwareSerial library mod 允许 8-O-1 com

c++ - 在多个源文件中访问相同的类实例

c++ - if-else 和三元运算符的不同行为

C++ 嵌入 lua 5.2 对 `luaL_newstate' 的 undefined reference (ubuntu 14.04,Netbeans)

linux - 缓存一致性及其解决方案

c++ - 单元测试引用关键部分类