samedi 3 décembre 2016

Thread run and join from separate threads

I have a shared_ptr object which is created in a thread. Inside this object there is a start function which creates another thread. And there is a stop function which holds and joins those internal thread. Is it safe to stop (call join) from any separate thread ?

TestThreadClass.cpp

namespace
{
    std::thread T1;
    std::atomic_bool workerFlag(true);
    void workerFunc()
    {
        while (workerFlag.load())
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
    }
}  //namespace

TestThreadClass::~TestThreadClass()
{
    stop();
}

void TestThreadClass::start()
{
    T1 = std::thread{workerFunc};
}
void TestThreadClass::stop()
{
    workerFlag.store(false);
    if (T1.joinable())
    {
        T1.join();
    }
}

main.cpp

namespace
{
    std::shared_ptr<TestThreadClass> mainObj;
    void workerFunc()
    {
        auto newObject = std::make_shared<TestThreadClass>();
        newObject->start();
        std::atomic_store(&mainObj, newObject);
    }

    void workerFunc2()
    {
        mainObj->stop();
    }
}  // namespace

int main(int argc, char** argv)
{
    std::thread t1{workerFunc};
    t1.join();
    t1 = std::thread{workerFunc2};
    t1.join();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire