12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-04 17:02:30
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在C++中,wait通常用于线程同步机制中,用于使当前线程进入等待状态,直到条件满足或者被通知后才继续执行。wait通常与mutex和condition_variable一起使用。具体用法如下:使用std:
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在C++中,wait
通常用于线程同步机制中,用于使当前线程进入等待状态,直到条件满足或者被通知后才继续执行。wait
通常与mutex
和condition_variable
一起使用。具体用法如下:
std::unique_lock<std::mutex>
对象对mutex
进行加锁。调用condition_variable
对象的wait
方法,将unique_lock
对象传入,使当前线程进入等待状态。在另一个线程中满足某个条件时,调用condition_variable
对象的notify_one
或notify_all
方法,通知等待的线程。等待的线程被通知后,wait
方法返回,继续执行。示例代码如下:
#include <iostream>#include <thread>#include <mutex>#include <condition_variable>std::mutex mtx;std::condition_variable cv;bool ready = false;void wait_func() {std::unique_lock<std::mutex> lck(mtx);while (!ready) {cv.wait(lck);}std::cout << "Thread is notified." << std::endl;}void notify_func() {std::this_thread::sleep_for(std::chrono::seconds(2));{std::lock_guard<std::mutex> lck(mtx);ready = true;}cv.notify_one();}int main() {std::thread t1(wait_func);std::thread t2(notify_func);t1.join();t2.join();return 0;}
在上面的示例中,wait_func
线程等待ready
状态变为true
,notify_func
线程在2秒后将ready
状态设置为true
并通知等待的线程。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19