Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a thread is NULL [closed]

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.

What I want to do is something like this:

#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;
}

But the if(opThread != NULL) line is obviously not correct.

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

Thanks -D

like image 325
Mich Avatar asked Aug 30 '25 17:08

Mich


1 Answers

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);
}
like image 71
Kerrek SB Avatar answered Sep 02 '25 18:09

Kerrek SB