c++ - 是否加入 std::thread 刷新内存?

标签 c++ multithreading c++11 synchronization c++-standard-library

考虑这个例子:

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

std::string some_variable;

void writer_thread()
{
    std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
    some_variable = "done";
}

int main()
{
    {
        std::thread w( &writer_thread );
        w.join();
    }

    std::cout << some_variable;
}

我是否有必要添加同步机制以确保从 main() 中正确读取 some_variable

换句话说:加入或销毁 std::thread 对象是否意味着刷新与其局部变量关联的内存?

最佳答案

join 提供必要的同步。在成功 join 之后您所做的任何事情都将与线程在结束之前所做的任何事情正确同步。

来自标准(C++11 30.3.1.5 [thread.thread.member]/5),指定thread::join的行为:

Synchronization: The completion of the thread represented by *this synchronizes with the corresponding successful join() return.

关于c++ - 是否加入 std::thread 刷新内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27109314/

相关文章:

C++ 抽象类型声明

c++ - 如何在线程创建和退出时调用函数?

c# - 如何制作具有连续 ID 的线程

linux - 在这种情况下,我应该在单独的线程中读取文件吗?

c++ - 模板类型推导

c++ - 在 C++ 中,我想创建一个循环,不断检查文件的大小,并在文件大小发生变化时执行某些操作

c++ - 多态对象复制

c++ - 将捕获的 lambda 作为函数指针传递

c++ - 为什么 alignas 说明符会在 Clang 上抛出错误?

c++ - 将非静态成员函数作为函数的参数传递