I want to pause and resume a thread from outside, and at any time (not at certain breakpoints, and thus wait and notify won't work).
For example, we create a thread in foo(), and then it keeps running. (the Thread could be any thread class similar to std::thread)
void A::foo() {
this->th = Thread([]{
// This thread runs a time-consuming job with many steps
// I hope to pause and resume it at any time outside ths thread (e.g. press a button)
});
}
I need to pause and resume the thread outside the thread, maybe by calling methods like this...
void A::bar() {
this->th->pause();
cout << "The thread is paused now" << endl;
}
void A::baz() {
this->th->resume();
cout << "The thread is resumed now" << endl;
}
How can I implement this in C ?
CodePudding user response:
@freakish said it can be done with pthread and signals, but no portable way.
In Windows, I just found SuspendThread(t.native_handle()) and ResumeThread(t.native_handle()) (where t is of type std::thread) are available. These would solve my problem.
