How to stop the thread execution in C++

后端 未结 3 2035
心在旅途
心在旅途 2020-12-22 03:06

I created one thread in my main program, thread execution has to stop once the main program will terminate. I am using reader.join(); to terminate the thread ex

3条回答
  •  Happy的楠姐
    2020-12-22 04:03

    thread.join() does not cause the thread to terminate, it waits until the thread ends. It's the responsibility of the thread to end its execution, for example by periodically checking for a certain condition, like a flag.

    You already have an atomic flag bReading, which appears to cause the thread to exit.

            if (queueInput.empty()) {
                mtxQueueInput.unlock();
                if (bReading.load())
                    continue;
                else
                    break;  // thread will exit when queue is empty and bReading == false
    

    So all you need is to set bReading = false in the outer thread before calling thread.join().

    bReading = false;
    reader.join();
    

    Note that bReading.store(false); inside your thread will have no effect.


    Note: you don't need to call atomic.load() and atomic.store(), you can just use them in your code, which will call load() and store() implicitly.

提交回复
热议问题