温馨提示×

C++ notify_all如何解决死锁

c++
小樊
99
2024-07-21 11:08:03
栏目: 编程语言

在 C++ 中使用 notify_all() 可能会导致死锁的情况,因为在多线程环境下,notify_all() 当前不会释放锁。这可能会导致线程在等待条件变量时陷入死锁。

为避免这种情况,可以使用 unique_lock 代替 lock_guard 来管理互斥锁的所有权。unique_lock 允许手动释放锁,并且提供了 wait() 方法来释放锁并等待条件变量的通知。

以下是一个使用 unique_lock 解决死锁问题的示例代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker_thread() {
    std::unique_lock<std::mutex> lock(mtx);
    while (!ready) {
        cv.wait(lock);
    }
    // do some work
}

void notify_thread() {
    std::unique_lock<std::mutex> lock(mtx);
    ready = true;
    cv.notify_all();
}

int main() {
    std::thread worker(worker_thread);
    std::thread notifier(notify_thread);

    worker.join();
    notifier.join();

    return 0;
}

在这个示例中,worker_thread 线程在等待条件变量时使用 cv.wait(lock) 来手动释放锁并等待通知。而 notify_thread 线程在修改条件变量并发出通知后,所有等待条件变量的线程将被唤醒。这样可以避免 notify_all() 导致的死锁情况。

0