我的代码如下:
class MyThread : public std::thread {
int a_;
public:
MyThread(int a)
: std::thread(&MyThread::run, this),
a_(a)
{ }
void run() {
// use a_
}
};
我想有自己的线程类,它有std::thread提供的所有方法,所以我让MyThread类继承std::thread。 在 MyThread 的构造函数中,我将其成员函数传递给 std::thread。编译没问题,但我担心在 std::thread 的构造函数中调用 run() 和初始化 a_ 之间存在竞争条件。
有没有办法让它安全?
最佳答案
不要那样做。 “Has-a”(组合)比“is-a”(继承)有很多优势。
class MyThread
{
std::thread _thread;
int _a;
public:
MyThread(int a) : _a(a)
{
_thread = std::thread([this] {run();});
}
void run()
{
// thread code here
};
void join()
{
_thread.join();
}
};
更好的方法是识别线程和该线程上的操作是两个不同的对象:
class WorkerOperation
{
int _a;
public:
WorkerOperation(int a) : _a(a)
{
}
void run()
{
// your code goes here
}
};
然后创建线程:
shared_ptr<WorkerOperation> spOp = make_shared<WorkerOperation>(42);
std::thread t = std::thread([spOp] {spOp->run();});
如果你真的需要配对操作和线程:
std::pair<WorkerOperation, std::thread> threadpair;
threadpair.first = spOp;
threadpair.second = std::move(t);
关于c++ - 继承std::thread时如何安全调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58279667/