【发布时间】:2017-07-18 17:24:12
【问题描述】:
看看下面的例子,
#include <iostream>
#include <thread>
class GPS
{
public:
GPS() { this->init(); }
~GPS() {m_thread.join();}
private:
std::thread m_thread;
void init() { m_thread = std::thread(&GPS::update,this); }
void update() { /*get data from gps sensor.*/ };
};
GPS myGPS;
int main()
{
return 0;
}
在全局范围内创建一个拥有自己线程的对象的后果是什么?这是安全的方法吗?如果否,假设对象必须是全局的并且具有独立线程,有哪些替代方案?谢谢。
【问题讨论】:
-
Is the main thread allowed to spawn a POSIX thread before it enters main()? 的可能重复项 - 问题的表述方式略有不同,但接受的答案非常好,并且与您的问题密切相关。另一种选择是在
main开头初始化的 Meyers 单例。 -
@Zulan 这不是 POSIX 线程,它是 std 线程。
-
阅读答案。
标签: c++ multithreading c++11 stdthread