Home C++ thread exit loop condition
Reply: 0

C++ thread exit loop condition

user1005
1#
user1005 Published in April 22, 2018, 3:07 am

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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304042 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO