2025年c++ 条件变量(c++ 条件变量 wait)

c++ 条件变量(c++ 条件变量 wait)std condition variable 的 wait 函数用于等待一个条件达成 它需要与 std unique lock std mutex 一起使用 以确保在等待期间互斥量被正确地锁定和解锁 以下是一个示例代码 演示了如何使用 std condition variable 的 wait 函数等待条件达成 cpp include iostream include thread include lt thread iostream std mutex

std::condition_variable的

wait

函数用于等待一个条件达成。它需要与std::unique_lock<std::mutex>一起使用,以确保在等待期间互斥量被正确地锁定和解锁。

以下是一个示例代码,演示了如何使用std::condition_variable的

wait

函数等待条件达成:

```cpp

#include <iostream>

#include <thread>

#include <condition_variable>

std::mutex mtx;

std::condition_variable cv;

bool condition = false;

void worker()

{

std::unique_lock<std::mutex> lock(mtx);

cv.

wait

(lock, []{ return condition; }); // 等待条件达成

// 条件达成后的操作

std::cout << "条件已达成,执行操作" << std::endl;

}

int main()

{

std::thread t(worker);

// 模拟条件达成

std::this_thread::sleep_for(std::chrono::seconds(2));

{

std::lock_guard<std::mutex> lock(mtx);

condition = true;

}

cv.notify_one(); // 通知等待的线程条件已达成

t.join();

return 0;

}

```

在上述示例中,worker函数是一个工作线程,它在等待条件达成之前会一直阻塞。在主线程中,通过改变condition的值,并调用cv.notify_one()来通知工作线程条件已达成。一旦条件达成,工作线程会被唤醒并执行相应的操作。

编程小号
上一篇 2025-02-19 23:27
下一篇 2025-02-24 17:57

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ri-ji/74454.html