c++ - 继承std::thread时如何安全调用成员函数

标签 c++ multithreading

我的代码如下:

  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/

相关文章:

c++ - opencv 将 2 个图像与 y 方向的偏移量结合起来

c# - 如何处理托管 C++ (/CLR) 中 #using 语句中的错误

java - 一个线程可以同时处理多个请求吗?

c# - 当 FindFiles 进程完成时发出通知

c++ - 无法使用在同一类中使用成员函数的线程进行编译

C++ 在临时类中创建数组

c++ - std::enable_if<> 错误

c++ - char数组-处理内存

c - 多线程编程中关于全局变量的一些问题

java - AdvertisingIdClient getAdvertisingIdInfo 被主线程阻塞