Pause and resume one C ++ thread in another

I have C ++ code with two threads. After event “A” in thread 2, thread 1 must be paused (suspended), several more tasks must be performed in thread 2 (for example, event “B”), and finally, thread 1 must be resumed. Is there any way to do this?

My code looks something like this:

HANDLE C; DWORD WINAPI A (LPVOID in) { while(1){ // some operation } return 0; } DWORD WINAPI B (LPVOID in) { while(1){ //Event A occurs here SuspendThread (C); //Event B occurs here ResumeThread (C); } return 0; } int main() { C = CreateThread (NULL, 0, A, NULL, 0, NULL); CreateThread (NULL, 0, B, NULL, 0, NULL); return 0; } 
+7
source share
2 answers

Hi, I have an example that I got inspiration from a cpp link. The example uses C ++ 11, so given that this question was not marked by win32, but C ++ and multithreading, I am posting something.

This is the original link first.

http://en.cppreference.com/w/cpp/thread/sleep_for

Now here is the code I received that solves the problem.

 #include <iostream> #include <string> #include <thread> #include <mutex> #include <condition_variable> std::mutex m; std::condition_variable cv; std::string data; bool ready = false; bool processed = false; void ThreadB_Activity() { // Wait until ThreadA() sends data { std::unique_lock<std::mutex> lk(m); cv.wait(lk, []{return ready;}); } std::cout << "Thread B is processing data\n"; data += " after processing"; // Send data back to ThreadA through the condition variable { std::lock_guard<std::mutex> lk(m); processed = true; std::cout << "Thread B signals data processing completed\n"; } cv.notify_one(); } void ThreadA_Activity() { std::cout<<"Thread A started "<<std::endl; data = "Example data"; // send data to the worker thread { std::lock_guard<std::mutex> lk(m); ready = true; std::cout << "Thread A signals data are ready to be processed\n"; } cv.notify_one();//notify to ThreadB that he can start doing his job // wait for the Thread B { std::unique_lock<std::mutex> lk(m); cv.wait(lk, []{return processed;}); } std::cout << "Back in Thread A , data = " << data << '\n'; std::this_thread::sleep_for( std::chrono::milliseconds( 1000 )); std::cout<<"end of Thread A"<<std::endl; } int main() { std::thread ThreadB(ThreadB_Activity); std::thread ThreadA(ThreadA_Activity); ThreadB.join(); ThreadA.join(); std::cout << "Back in main , data = " << data << '\n'; return 0; } 

Hope this helps, any comments are welcome :-)

+8
source

Since you seem to be using win32, you can use event

If you want to do something like this in pthreads, there is one here.

In both cases, thread A will check the condition / event (and wait if it is set or continue if it is not), and thread B will set and clear the condition / event. Note that you may also need a mutex between threads A and B depending on what they do, can they hurt each other?

0
source

All Articles