是否加入std :: thread刷新内存? [英] Does joining a std::thread flush memory?

查看:102
本文介绍了是否加入std :: thread刷新内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

#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吗?

Is it necessary for me to add a synchronization mechanism to ensure that some_variable is correctly read from main() ?

用不同的方式说:加入或破坏std::thread对象是否暗示与其局部变量关联的内存已清空?

Said differently: does joining or destructing a std::thread object imply that the memory associated to its local variable is flushed?

推荐答案

join提供了必要的同步.成功执行join之后所做的任何操作都将与线程在结束之前所做的任何操作正确地同步.

join provides the necessary syncronisation. Anything you do after a successful join will be correctly synchronised with anything the thread did before ending.

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

From the standard (C++11 30.3.1.5 [thread.thread.member]/5), specifying the behaviour of thread::join:

同步: *this表示的线程的完成与相应的join()成功返回同步.

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

这篇关于是否加入std :: thread刷新内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆