winapiwrapper
winapiwrapper

Reputation: 145

C++ thread exit loop condition

I want to create a counter inside a thread, and stop it by changing the value of a boolean.

Here's my code:

#include <unistd.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

using namespace std;

bool _terminateT;
mutex mtx;
condition_variable cv;

void counter()
{
    unique_lock<mutex> lock(mtx);
    int i(0);

    while(!_terminateT)
    {
        cout<<i<<endl;
        i++;
        cv.wait(lock);
    }
}

int main()
{
    _terminateT = false;
    thread t(counter);

    sleep(4);
    {
        lock_guard<mutex> lckg(mtx);
        _terminateT = true;
    }

    cv.notify_one();

    cout<<"main"<<endl;
    t.join();

    return 0;
}

The problem is that the loop is blocked by the wait function. Is there a way to protect the _terminateT variable without blocking the while loop?

Upvotes: 0

Views: 972

Answers (1)

stoper
stoper

Reputation: 186

For that code you don't need condition variable. A mutex protecting the boolean variable would be enough. It should be locked and unlocked in loop check.

In fact, in that particular example where there is no risk of data race (you are just setting variable from 0 to other value once), you could even skip the mutex and set variable in an unprotected manner - the loop will always terminate, as even if thread runs on other core than main function, its cache will get the correct changed value eventually. Situation would be different if you shared other data between threads.

Upvotes: 2

Related Questions