C++11单/多线程总结(三十五)
2023-09-14 09:09:57 时间
1.代码示例
#include <iostream>
#include <thread>
#include <mutex>
#include <future>
#include <condition_variable>
#include <queue>
#include <chrono>
//1.thread usage demo
#if 0
void foo(){
std::cout << "hello" << std::endl;
}
int main(){
std::thread t(foo);
t.join();
return 0;
}
#endif
//2.mutex usage demo
#if 0
std::mutex mtx;
void block_area(){
std::unique_lock<std::mutex> lock(mtx);
//...临界区
}
int main(){
std::thread thd1(block_area);
thd1.join();
return 0;
}
#endif
#if 0
//3.thread Asynchrony operation
int main()
{
//将一个返回值为7的 lambda 表达式封装到 task 中
//std::packaged_task 的模板参数为要封装函数的类型
std::packaged_task<int()> task([](){return 7;});
//获得 task 的 future
std::future<int> result = task.get_future(); // 在一个线程中执行 task
std::thread(std::move(task)).detach(); std::cout << "Waiting...";
result.wait();
//输出执行结果
std::cout << "Done!" << std:: endl << "Result is " << result.get() << '\n';
}
#endif
//4.producer and consumer model demo.
#if 1
int main()
{
// 生产者数量
std::queue<int> produced_nums;
// 互斥锁
std::mutex m;
// 条件变量
std::condition_variable cond_var;
// 结束标志
bool done = false;
// 通知标志
bool notified = false;
// 生产者线程
std::thread producer([&]() {
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
// 创建互斥锁
std::unique_lock<std::mutex> lock(m);
std::cout << "producing " << i << '\n';
produced_nums.push(i);
notified = true;
// 通知一个线程
cond_var.notify_one();
}
done = true;
cond_var.notify_one();
});
// 消费者线程
std::thread consumer([&]() {
std::unique_lock<std::mutex> lock(m);
while (!done) {
while (!notified) { // 循环避免虚假唤醒
cond_var.wait(lock);
}
while (!produced_nums.empty()) {std::cout << "consuming " << produced_nums.front() << '\n';
produced_nums.pop();
}
notified = false;
}
});
producer.join();
consumer.join();
}
#endif
相关文章
- 【C/C++学院】0826-文件重定向/键盘输入流/屏幕输出流/字符串输入输出/文件读写简单操作/字符文件读写二进制与文本差别/get与getline挖掘数据/二进制与文本差别/随机位置/多线程初级
- C++ thread类多线程编程
- (C++)String的用法
- C++多线程编程笔记
- C++ 用DEV-C++建一个Windows窗口程序带文本框和命令按钮
- C++ Beep()演奏简谱的改进以及实现背景音乐
- Open3D (C++) 点云添加高斯噪声
- c++模板篇01之函数模板
- C++ 多线程编程的基本概念和方法
- C++多线程基础入门
- C++设计模式:MVC 模式
- 在Qt(C++)中使用QThread实现多线程
- 复习C++标准库多线程的基本使用
- C++多线程使用条件变量
- C++ 单例的饿汉式和懒汉式及懒汉式遇到多线程的终极处理方式
- C++实现微信WeChat网页接口推送股票报警消息
- C++ in Chromium 101 - Codelab 编程开始 bind 多线程 回调
- Chromium 基础库使用说明(结合c++ 17入门经典 好好理解 非常重要)
- C++并行计算之OpenMP多线程
- C++多态使用(一)
- key-value 多线程server的Linux C++实现
- C++ 多线程
- PCL RANSAC拟合空间直线(C++详细过程版)