暂停std :: thread直到函数完成

时间:2013-09-23 19:10:42

标签: c++ multithreading c++11

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

构造

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

在我的应用程序中的某个时刻,我必须暂停该线程并调用一个函数,并且在执行该函数后我必须恢复该线程。让我们说它发生在这里:

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

我尝试使用另一个功能为functionToBeCalled()的线程并使用thread::join但由于某种原因无法执行此操作。

如何暂停某个帖子或如何使用thread::join暂停一个帖子直到另一方完成?

2 个答案:

答案 0 :(得分:4)

我认为你不能轻易(以标准的方式)“暂停”一些线程,然后重新开始。我想如果你使用的是一些Unix风格的操作系统,你可以发送SIGSTOP和SIGCONT,但除此之外,你应该使用互斥锁和锁定正确地标记someFunc()内的原子部分,使用锁定的functionToBeCalled()包裹相应的互斥锁:

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

并在函数内部:

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
    }
}

并且在致电functionToBeCalled()时:

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

答案 1 :(得分:2)

您可以使用条件变量。这里给出了一个类似于你的情况的例子: http://en.cppreference.com/w/cpp/thread/condition_variable

相关问题