当前位置: 首页 > news >正文

[C++11]_[初级]_[工作线程如何监听主线程条件变量wait_for方法的使用]

场景

  1. 在开发多线程程序时,有时候需要启动一个线程来监听外部进程的执行情况,并且在指定时间如果还没运行结束就强制结束外部线程。那么C++标准库有这种监听线程并能在超时时提示的方法吗?

说明

  1. C++11<condition_variable>里就可以用条件变量来等待信号通知, 并设置超时时间。 超时时间的含义是,wait_for在超时达到时会自动唤醒mutex并不断尝试获取锁,当锁被获取时,进入下一条代码。
template< class Lock, class Rep, class Period >std::cv_status wait_for( Lock& lock,const std::chrono::duration<Rep, Period>& rel_time );
mutex.lock();
cond.wait_for(mutex, std::chrono::seconds(10));
mutex.unlock();
  1. wait_for的重载函数还有一个返回值是bool的函数对象。这个函数对象是为了避免虚假的唤醒,比如被错误的notify_one唤醒时,需要判断是否返回true, 如果返回true, 那么结束等待,否则继续等到到超时。 这个带Predicate参数的实现等同于
    wait_until(lock, std::chrono::steady_clock::now() + rel_time, std::move(pred));.[1]
template< class Lock, class Rep, class Period, class Predicate >bool wait_for( Lock& lock, const std::chrono::duration<Rep, Period>& rel_time,Predicate pred );
  1. 以上的Predicate函数对象的作用等同于以下的实现:[2].
  • 进入等待前先判断Predicate是否为true, 如果为false,进度等待。
  • 如果等到超时,直接返回Predicate的值,即执行下一行代码。
  • 如果非超时的唤醒,那么返回第一步。
while (!pred())if (wait_until(lock, abs_time) == std::cv_status::timeout)return pred();
return true;.
  1. 注意,使用条件变量唤醒时,不需要加锁。cond1.notify_one(); [3]因为如果对通知操作进行加锁,那么通知发生时,等待线程唤醒后会尝试获取锁,但是获取不到会迅速阻塞,因为被通知的线程需要等待通知线程解锁。
The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); 
in fact doing so is a pessimization, since the notified thread would immediately block again, 
waiting for the notifying thread to release the lock. 
However, some implementations (in particular many implementations of pthreads) recognize this situation and 
avoid this "hurry up and 
wait" scenario by transferring the waiting thread from the condition variable's queue directly to the queue of the mutex within the notify call, without waking it up. 

例子

// test-wait-for.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//#include <iostream>
#include <condition_variable>
#include <thread>
#include <mutex>
#include <chrono>using namespace std;void work_1(condition_variable_any& cond,mutex& mutex)
{mutex.lock();cond.wait_for(mutex, std::chrono::seconds(10));mutex.unlock();
}void TestWaitFor_1()
{condition_variable_any cond1;mutex mutex1;auto beg =  std::chrono::system_clock::now();thread t1(work_1,std::ref(cond1),std::ref(mutex1));std::this_thread::sleep_for(std::chrono::seconds(3));//cond1.notify_one();t1.join();std::chrono::duration<double> seconds = std::chrono::system_clock::now() - beg;printf("TestWaitFor_2 elapsed_seconds: %fs\n", seconds);
}void work_2(condition_variable_any& cond,mutex& mutex,bool& bFinish)
{mutex.lock();cond.wait_for(mutex, std::chrono::seconds(10), [&bFinish]{return bFinish; });mutex.unlock();
}void TestWaitFor_2(bool bValue)
{condition_variable_any cond1;mutex mutex1;bool bFinish = false;auto beg =  std::chrono::system_clock::now();thread t1(work_2,std::ref(cond1),std::ref(mutex1),std::ref(bFinish));std::this_thread::sleep_for(std::chrono::seconds(3));// 用来处理虚假的唤醒,即如果没有到timeout就收到唤醒且bFinish还为false的话,wait会继续。bFinish = bValue; // 想让notify_one的唤醒生效,必须bFinish = true;cond1.notify_one();t1.join();std::chrono::duration<double> seconds = std::chrono::system_clock::now() - beg;printf("TestWaitFor_2 elapsed_seconds: %fs\n", seconds);
}int main()
{std::cout << "Hello World!\n";std::cout << "\n==== TestWaitFor_1 ====" << endl;TestWaitFor_1();std::cout << "\n=== TestWaitFor_2 ==== bFinish = false" << endl;TestWaitFor_2(false);std::cout << "\n=== TestWaitFor_2 ==== bFinish = true" << endl;TestWaitFor_2(true);
}

输出

Hello World!==== TestWaitFor_1 ====
TestWaitFor_2 elapsed_seconds: 10.012182s=== TestWaitFor_2 ==== bFinish = false
TestWaitFor_2 elapsed_seconds: 10.008821s=== TestWaitFor_2 ==== bFinish = true
TestWaitFor_2 elapsed_seconds: 3.030650s

参考

  1. wait_for

  2. wait_util

  3. notify_one

  4. pthread_cond_signal

http://www.lryc.cn/news/519724.html

相关文章:

  • Openstack持久存储-Swift,Cinder,Manila三者之间的区别
  • 深度学习第三弹:python入门与线性表示代码
  • 解决报错记录:TypeError: vars() argument must have __dict__ attribute
  • SpringBoot 原理篇(day14)
  • Vscode辅助编码AI神器continue插件
  • Type-C单口便携显示器-LDR6021
  • 青少年编程与数学 02-006 前端开发框架VUE 19课题、内置组件
  • 腾讯云AI代码助手编程挑战赛 - 使用 JavaScript 构建一个简易日历
  • Xcode 正则表达式实现查找替换
  • 学习flv.js
  • FreePBX 17 on ubuntu24 with Asterisk 20
  • 【算法】算法大纲
  • 【MySQL】SQL菜鸟教程(一)
  • 安装本地测试安装apache-doris
  • 【Apache Paimon】-- 13 -- 利用 paimon-flink-action 同步 mysql 表数据
  • IOS HTTPS代理抓包工具使用教程
  • 在 Ubuntu 22.04 上从 Wayland 切换到 X11的详细步骤
  • 【Linux】4.Linux常见指令以及权限理解(2)
  • ffmpeg aac s16 encode_audio.c
  • vue3监听器
  • 03-51单片机定时器和串口通信
  • 系统架构设计师考点—项目管理
  • 代码随想录算法训练营第三十二天|509.斐波那契数、70.爬楼梯、746.使用最小花费爬楼梯
  • 【2024年华为OD机试】 (A卷,100分)- 总最快检测效率(Java JS PythonC/C++)
  • 【大数据】Apache Superset:可视化开源架构
  • LabVIEW调用不定长数组 DLL数组
  • MySQL 17 章——触发器
  • 面向对象分析与设计Python版 面向对象设计方法
  • GB/T 19582.1-2008主要内容
  • [石榴翻译] 维吾尔语音识别 + TTS语音合成