如何检查线程是否为NULL [英] How can I check if a thread is NULL

查看:145
本文介绍了如何检查线程是否为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个类的几个实例运行一个简单的操作,并且我想在每个类的单独线程中运行此操作. 如果该类的同一实例要再次运行该操作,则它必须等待该实例中的上一个操作完成. 但是,该类的另一个实例应该能够在第一个实例执行相同操作时启动其操作.

I'm running a simple operation with a few instances of a class and I want to run this operation in a separate thread for each class. If that same instance of that class wants to run that operation again, it has to wait for the previous operation within that instance to finish. However, another instance of the class should be able to start it's operation while the first instance is performing the same operation.

我想做的是这样的:

#include <thread>
class MyClass
{
    void Operation(){Sleep(10000);}
    void LaunchOperation()
    {
        if(opThread != NULL) //Pseudo Code line
            opThread.join();
        opThread = std::thread(&MyClass::Operation, this);
    }

    std::thread opThread;
}

但是if(opThread != NULL)行显然不正确.

是否有正确的替代方法?还是我采用了错误的方法?

Is there a correct substitution for this, or am I taking the wrong approach?

谢谢 -D

推荐答案

您可能正在寻找 joinable 成员函数:

You are probably looking for the joinable member function:

void f(std::thread & t)
{
    if (t.joinable())
    {
        t.join();
    }
    t = std::thread(&X::foo, &obj, 1, 2, 3);
}

这篇关于如何检查线程是否为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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