我正在使用一个封装了 thread_group 的类,对此有一些疑问
class MyGroup{
private:
boost::this_thread::id _id;
boost::thread::thread_group group;
int abc;
//other attributes
public:
void foo();
};
在类构造函数中,我启动了 N 个线程
for (size_t i=0;i<N;i++){
group.add(new boost::thread(boost::bind(&foo,this)));
}
void foo(){
_id = boost::this_thread::get_id();
//more code.
abc++ //needs to be sync?
}
所以,这是我的问题。
类属性是否需要同步?
是否每个线程都有不同的 ID?例如,如果我有
void bar(){
this->id_;
}
这会导致每个线程的 ID 不同,还是每个线程都相同?
提前致谢!
最佳答案
是的,即使您使用线程创建助手作为插入力,共享数据访问也必须受到保护。
最终它们都会同时执行相同的代码,库无法对您拥有和管理的变量进行保护。
如果 this->_id 打印当前线程 ID 那么是的,它会在不同的线程访问它时打印不同的值。
关于c++ - 封装boost thread_group。关于ids和同步的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1472330/