当前位置:网站首页>std::condition_ variable::wait_ for
std::condition_ variable::wait_ for
2022-06-13 05:02:00 【Snow * sleet * snow】
wait:https://blog.csdn.net/qq_34999565/article/details/120874408?utm_source=app&app_version=4.17.0&code=app_1562916241&uLinkId=usr1mkqgl919blen
Examples of use , and wait Is the difference between the wait_for You can set a timeout
#include <iostream>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
std::condition_variable cv;
std::mutex cv_m;
int i;
void waits(int idx)
{
std::unique_lock<std::mutex> lk(cv_m);
if(cv.wait_for(lk, idx*100ms, []{
return i == 1;}))
std::cerr << "Thread " << idx << " finished waiting. i == " << i << '\n';
else
std::cerr << "Thread " << idx << " timed out. i == " << i << '\n';
}
void signals()
{
std::this_thread::sleep_for(120ms);
std::cerr << "Notifying...\n";
cv.notify_all();
std::this_thread::sleep_for(100ms);
{
std::lock_guard<std::mutex> lk(cv_m);
i = 1;
}
std::cerr << "Notifying again...\n";
cv.notify_all();
}
int main()
{
std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals);
t1.join();
t2.join();
t3.join();
t4.join();
}
Output :
Thread 1 timed out. i == 0
Notifying…
Thread 2 timed out. i == 0
Notifying again…
Thread 3 finished waiting. i == 1
2
3
边栏推荐
- All blog navigation
- Analysis of the principle of V-model and its application in user defined components
- QT client development -- driver loading problem of connecting to MySQL database
- BM1Z002FJ-EVK-001开机测评
- shell变量学习笔记
- Clause 33: decltype is used for auto & type formal parameters, with std:: forward
- Binary search and binary answer
- Chapter 14 introduction: memory operation API
- Four methods for judging JS data types and user-defined methods
- Spice story
猜你喜欢
[JS solution] leedcode 200 Number of islands
System file interface open
C language learning log 10.19
Section 3 - functions
Chapter 13 abstraction: address space
Kaggle time series tutorial
自动评教脚本使用的配置
Reductive elimination
[JS solution] leedcode 117 Populate the next right node pointer II for each node
Sort (internal sort) + external sort
随机推荐
C language learning log 1.19
【线程/多线程】线程的执行顺序
All blog navigation
Ruoyi cloud startup tutorial (hand-held graphics)
lookup
Section 6 - pointers
Construction problem of D Xiaohong
使用EasyDarwin+FFmpeg实现rtsp推流
Advanced C language - Section 1 - data storage
关于匿名内部类
Clause 33: decltype is used for auto & type formal parameters, with std:: forward
Clause 48: understand template metaprogramming
Handwritten promise and its method, with detailed notes
Recursion and recursion
JS to realize the conversion between string and array and an interview question
2021tami/ image processing: exploiting deep generative priority for versatile image restoration and manipulation
[leetcode]- sliding window
135. distribute candy
Robot pose description and coordinate transformation
QT client development -- driver loading problem of connecting to MySQL database