当前位置:网站首页>rust 使用tokio的Notify 和timeout实现类似可超时条件变量的效果
rust 使用tokio的Notify 和timeout实现类似可超时条件变量的效果
2022-04-23 07:38:00 【聆听--风雨】
Notify配合timeout,在异步编程中实现类似可超时条件变量的效果。代码很简单,如下:
use std::{sync::Arc, time::Duration};
use tokio::{sync::Notify, time::sleep};
#[tokio::main]
async fn main() {
let notify = Arc::new(Notify::new());
let notify_clone = notify.clone();
let notify_clone2 = notify.clone();
let notify_clone3 = notify.clone();
tokio::spawn(async move {
sleep(Duration::from_secs(2)).await;
notify_clone.notify_one(); //两秒后通知
println!("notify one")
});
tokio::spawn(async move {
if let Err(_) = tokio::time::timeout(Duration::from_secs(1), notify_clone2.notified()).await
{
println!("time out!"); //1秒后未收到通知而超时
}
});
tokio::spawn(async move {
if let Ok(_) = tokio::time::timeout(Duration::from_secs(3), notify_clone3.notified()).await
{
println!("recive notifyed!"); //等待三秒,但是在第二秒的时候收到了通知,会直接返回成功
}
})
.await
.unwrap();
}
版权声明
本文为[聆听--风雨]所创,转载请带上原文链接,感谢
https://chongfei.blog.csdn.net/article/details/124341012
边栏推荐
- freertos学习02-队列 stream buffer message buffer
- LeetCode中等题之旋转函数
- Kubernetes in browser and IDE | interactive learning platform killercoda
- 线程的调度(优先级)
- QT reading and writing XML files
- LeetCoed18. Sum of four numbers
- Common regular expressions
- CGM优化血糖监测管理——移宇科技亮相四川省国际医学交流促进会
- Compiler des questions de principe - avec des réponses
- 2022.4.11-4.17 AI行业周刊(第93期):AI行业的困局
猜你喜欢
社区团购小程序源码+界面diy+附近团长+供应商+拼团+菜谱+秒杀+预售+配送+直播
Weekly leetcode - 06 array topics 7 ~ 739 ~ 50 ~ offer 62 ~ 26 ~ 189 ~ 9
The annotation is self-defined by implementing the parameter parser handlermethodargumentresolver interface
[appium] encountered the problem of switching the H5 page embedded in the mobile phone during the test
One click cleanup of pycharm and jupyter cache files under the project
校园转转二手市场源码下载
[learning] audio and video development from scratch (9) -- nuplayer
Transformer-XL: Attentive Language ModelsBeyond a Fixed-Length Context 论文总结
怎么读书读论文
WordPress爱导航主题 1.1.3 简约大气网站导航源码网址导航源码
随机推荐
怎么读书读论文
Detailed explanation of ansible automatic operation and maintenance (I) installation and deployment, parameter use, list management, configuration file parameters and user level ansible operating envi
关于ORB——SLAM运行中关键帧位置越来越近的异常说明
An example of network communication based on TCP / IP protocol -- file transmission
input元素添加监听事件
An idea plug-in that doesn't work, but can install X
Qt读取路径下所有文件或指定类型文件(含递归、判断是否为空、创建路径)
nn.Module类的讲解
NFT ecological development of Ignis public chain: unicorn Donation and development of Art
vslam PPT
QFileDialog select multiple files or folders
[effective go Chinese translation] function
如何保护开源项目免遭供应链攻击-安全设计(1)
浅谈ES6尾调优化
Common regular expressions
C language learning record -- use and analysis of string function (2)
redis主从服务器问题
剑指offer day24 数学(中等)
项目上传部分
Interesting JS code