c++ - 暂停 std::thread 直到函数完成

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

最佳答案

我不认为您可以轻松地(以标准方式)“暂停”一些线程,然后恢复它。我想如果你使用的是一些 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/

相关文章:

c++ - 如何每天只运行一次 if 语句,如果它在 Arduino 上为真

c++ - 图形在空间中的方向

c - 大家好,我在下面的程序中遇到段错误,但我无法弄清楚

java - 如何在不同的线程中使用 JProgressBar?

C++ 多线程 - 线程安全代码

c++ - 创建二维动态数组的函数

c++ - 使用 Hoare 分区方案的快速排序算法返回原始未排序列表

c++ - 我们如何使用引用类型实例化模板函数?

c++ - 有序和无序映射

c++ - 在 C++ 中组织涉及具有有限范围和模板的 const 引用的代码的好方法