The right way to stop workflow

Hi, I am trying to find the best peaceful way to stop the workflow. I have the following code:

class test{
  public:
test() {}
~test() {}

std::atomic<bool> worker_done;


int a;
void pr() {
    while (true) {
        if (worker_done) {
            break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        printf("%d \n", a++);
    }
}

std::thread* m_acqThread;
void continuous() {
    m_acqThread = new std::thread(&test::pr, this);
}

void stopThread(){
    if (m_acqThread) {
        if (m_acqThread->joinable())
            m_acqThread->join();
        delete m_acqThread;
        m_acqThread = nullptr;
    }
}


};


int main(){

test t;
t.continuous();

std::this_thread::sleep_for(std::chrono::milliseconds(2000));
t.worker_done = true;

t.stopThread();


std::string str;
std::cin.clear();
getline(std::cin, str);
return 0;

Is there a better way to notify a worker thread of a termination other than setting worker_done to be true?

thank

+4
source share
1 answer

Everything is fine with you: if you have threadone that starts when your program opens, and as you close your program, you need to stop it, using atomic<bool>is the right way to do this.

You can also use it std::atomic_flaglike this:

#include <thread>
#include <atomic>
#include <iostream>

std::atomic_flag lock;
int n = 0;

void t()
{
    while (lock.test_and_set())
    {
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
    }
}

int main()
{
    lock.test_and_set();
    std::thread t(&t);
    std::this_thread::sleep_for(std::chrono::seconds(2));
    lock.clear();
    t.join();
    std::cout << n << std::endl;
    std::cin.get();
}

, atomic_flag atomic<bool>, atomic<bool> , :

std::atomic<bool> runThread;
int n = 0;

void t()
{
    while (runThread)
    {
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
    }
}

int main()
{
    runThread = true;
    std::thread t(&t);
    std::this_thread::sleep_for(std::chrono::seconds(2));
    runThread = false;
    t.join();
    std::cout << n << std::endl;
    std::cin.get();
}
+2

Source: https://habr.com/ru/post/1683851/


All Articles