lhbortho
lhbortho

Reputation: 177

C++ suspend a thread and reactivate via a different thread

I haven't done much multi threading so I didn't know quite how to search for this question. It might have been answered already, I just didn't know what I was looking for specifically enough.

Basically I am hoping for a way to suspend a thread at a specific point in its execution. I then want to be able to resume the thread right after where it got suspended via a different thread.

Is there anything like that on windows?

Upvotes: 3

Views: 2774

Answers (2)

Alessandro Ogheri
Alessandro Ogheri

Reputation: 1

sorry but just doing

#include<iostream>
#include<thread>
#include<condition_variable>
#include<mutex>
std::condition_variable cv;
std::mutex lock;
void foo() {
    std::unique_lock<std::mutex> ulock(lock);
    cv.wait(ulock);
    std::cout << "Thread Complete" << std::endl;
}
void bar() {
    cv.notify_all();
}
int main()
{
    std::thread second(bar);
    std::thread first(foo);
    
    first.join();
    second.join();
    return 0;
}

so for example starting "second" as..ehr... first

this LOCKS in visual studio , for example..

(what I expect, as we notify BEFORE someone is waiting for the notification...)

Upvotes: 0

Jayson Boubin
Jayson Boubin

Reputation: 1504

Try using a std::condition_variable. Condition variables are 'synchronization primitives" that can be used to block threads. You can find more info on condition variables here: http://en.cppreference.com/w/cpp/thread/condition_variable

Below is an example of a quick C++ program that demonstrates the behavior in question. You can block and unblock a thread from another thread like this:

#include<iostream>
#include<thread>
#include<condition_variable>
#include<mutex>
std::condition_variable cv;
std::mutex lock;
void foo(){
        std::unique_lock<std::mutex> ulock(lock);
        cv.wait(ulock);
        std::cout<<"Thread Complete"<<std::endl;
}
void bar(){
        cv.notify_all();
}
int main()
{
        std::thread first(foo);
        std::thread second(bar);
        first.join();
        second.join();
        return 0;
}

Upvotes: 1

Related Questions