I want the main
function to stop function_
when an event occurs (after 1ms in this example). The problem I have is that function_
immediately relock the mutex without letting the main
function to get it.
#include <thread>
#include <mutex>
#include <iostream>
#include <chrono>
using namespace std;
void function_(volatile bool *ptrStop, mutex *ptrMtx) {
for (int i = 0; i < 10; i++) {
ptrMtx->lock();
if (*ptrStop) {
ptrMtx->unlock();
return;
}
//doSomething();
this_thread::sleep_for(chrono::milliseconds(1));
cout << "Iteration " << i << endl;
ptrMtx->unlock();
//this_thread::sleep_for(chrono::milliseconds(1));
}
return;
}
int main() {
volatile bool stop = 0;
mutex mtx;
thread functionThread(function_, &stop, &mtx);
this_thread::sleep_for(chrono::milliseconds(1));
mtx.lock();
stop = 1;
mtx.unlock();
cout << "Changed boolean variable value" << endl;
functionThread.join();
system("pause");
return 0;
}
I got the following output :
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9
Changed boolean variable value
What I want is to only do 1 or 2 iterations of function_
only (therefor let the main
take the mutex). How can I do that ? I heard about the std::condition_variable
but I couldn't figure a way to make what I want.
Moreover, if doSomething()
is uncommented and takes a long time to return, is there an easy way to kill the thread or force it to join without modifying what is in doSomething
function ?
std::condition_variable
? It should be what you want to use. – NathanOliverfunction_
beforemtx.lock()
is reached in the main thread. – Jensstd::condition_variable
? It should be easy to extend the example such that it does what you want. You just need a stop flag and a loop in the worker thread. – Jenslock
andunlock
. Use eitherstd::unique_lock
orstd::lock_guard
as appropriate. – Jive Dadson