1
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暂停一个线程直到另一个线程完成?

4

2 回答 2

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
于 2013-09-23T19:25:22.773 回答
2

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

于 2013-09-23T19:14:15.973 回答