khajvah
khajvah

Reputation: 5090

Pausing std::thread until a function finishes

class Class {
public:
    Class ();
private:
    std::thread* updationThread;
};

Constructor:

Class::Class() {
    updationThread = new std::thread(&someFunc);
}

At some point in my application, I have to pause that thread and call a function and after execution of that function I have to resume the thread. Let's say it happens here:

void Class::aFunction() {
     functionToBeCalled(); //Before this, the thread should be paused
     //Now, the thread should be resumed.
}

I have tried to use another thread with function functionToBeCalled() and use thread::join but was unable to do that for some reason.

How can I pause a thread or how can I use thread::join to pause a thread until the other finishes?

Upvotes: 1

Views: 6816

Answers (2)

Rémi
Rémi

Reputation: 3745

You can use a condition variable. An example similar to your situation is given there: http://en.cppreference.com/w/cpp/thread/condition_variable

Upvotes: 2

lvella
lvella

Reputation: 13443

I don't think you can easily (in a standard way) "pause" some thread, and then resumes it. I imagine you can send SIGSTOP and SIGCONT if you are using some Unix-flavored OS, but otherwise, you should properly mark the atomic parts inside someFunc() with mutexes and locks, an wraps functionToBeCalled() with a lock on the corresponding mutex:

std::mutex m; // Global mutex, you should find a better place to put it
              // (possibly in your object)

and inside the function:

void someFunc() {
    // I am just making up stuff here
    while(...) {
        func1();

        {
           std::lock_guard<std::mutex> lock(m); // lock the mutex
           ...; // Stuff that must not run with functionToBeCalled()
        } // Mutex unlocked here, by end of scope
    }
}

and when calling functionToBeCalled():

void Class::aFunction() {
    std::lock_guard<std::mutex> lock(m); // lock the mutex
    functionToBeCalled();
} // Mutex unlocked here, by end of scope

Upvotes: 4

Related Questions