当前位置:网站首页>Trust uses Tokio's notify and timeout to achieve the effect similar to the timeout condition variable
Trust uses Tokio's notify and timeout to achieve the effect similar to the timeout condition variable
2022-04-23 08:24:00 【Listen to the wind and rain】
Notify coordination timeout, In asynchronous programming, it can achieve the effect similar to timeout condition variable . The code is simple , as follows :
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(); // Notify in two seconds
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 Timeout without notification after seconds
}
});
tokio::spawn(async move {
if let Ok(_) = tokio::time::timeout(Duration::from_secs(3), notify_clone3.notified()).await
{
println!("recive notifyed!"); // Wait three seconds , But in the second second second, I received the notice , Will directly return success
}
})
.await
.unwrap();
}
版权声明
本文为[Listen to the wind and rain]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230738446929.html
边栏推荐
猜你喜欢

clang 如何产生汇编文件

谈谈那些基础但不简单的股票数据

跨域配置报错: When allowCredentials is true, allowedOrigins cannot contain the special value “*“

Failed to convert a NumPy array to a Tensor(Unsupported Object type int)

Qt利用QtXlsx操作excel文件

如何保护开源项目免遭供应链攻击-安全设计(1)

程序,进程,线程;内存结构图;线程的创建和启动;Thread的常用方法

CSV column extract column extraction

mysql查询字符串类型的字段使用数字类型查询时问题

Vowel substring in statistical string of leetcode simple problem
随机推荐
My heart's broken! A woman's circle of friends envied others for paying wages on time and was fired. Even her colleagues who liked her were fired together
Search the complete navigation program source code
数据的删除和修改操作(mysql)
LeetCode简单题之三除数
Idea: export Yapi interface using easyyapi plug-in
总线结构概述
Qtablewidget header customization and beautification developed by pyqt5 (with source code download)
LeetCode中等题之旋转函数
项目上传部分
stm32以及freertos 堆栈解析
npm安装yarn
Qt利用QtXlsx操作excel文件
What is RPC
ASAN 极简原理
校园转转二手市场源码下载
Green apple film and television system source code film and television aggregation film and television navigation film and television on demand website source code
Notes on English class (4)
Vowel substring in statistical string of leetcode simple problem
Multi vision slam
【解释】get ORA-12838: cannot read/modify an object after modifying it in parallel