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
暂停一个线程直到另一个线程完成?
最佳答案
我不认为您可以轻松地(以标准方式)“暂停”一些线程,然后恢复它。我想如果你使用的是一些 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
关于c++ - 暂停 std::thread 直到函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18966948/