C++并行开发11- std__atomic续谈、std__async深入谈
原子操作续谈
std::atomic<int> g_value = 0; //原子操作
void my_thread() {
for (int i = 0; i < 1000000; i++) {
g_value++; //支持原子操作
g_value+=1; //支持原子操作
g_value = g_value + 1; //不支持原子操作
}
}
std::async深入谈
F:/网站备份-20221127/zhouaq_backup_20221127.com/zhouaq.com/wp-content/p://zhouaq.com/wp-./uploads/2020/10/wp_editor_md_3264c3613be8ad76733550edd28c5bb3.jpg)](http:./uploads/2020/10/wp_editor_md_3264c3613be8ad76733550edd28c5bb3.jpg)F:/网站备份-20221127/zhouaq_backup_20221127.com/zhouaq.com/wp-content/p://zhouaq.com/wp-
content/uploads/2020/10/wp_editor_md_5a1d3ba8bea412f86fd61b09424d9d0f.jpg)](http://zhouaq.com/wp-
content/uploads/2020/10/wp_editor_md_5a1d3ba8bea412f86fd61b09424d9d0f.jpg)
通过wait_for判断当前是否创建新线程
#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include <list>
#include <mutex>
#include <future> //引入std::future头文件
using namespace std;
int my_thread() {
cout << "mythread start" << " threadid is = " << std::this_thread::get_id() << endl;
std::chrono::milliseconds dura(5000); //休息了5s
std::this_thread::sleep_for(dura);
cout << "over " << endl;
return 5;
}
int main() {
cout << "main " << "thread id is " << std::this_thread::get_id() << endl;
std::future<int> result = std::async(my_thread); //async:异步;
cout << "continue " << endl;
//枚举类型
//std::future_status status = result.wait_for(std::chrono::seconds(6)); //等待1s
std::future_status status = result.wait_for(0s); //(std::chrono::seconds(6)); //等待1s //重载了后缀s
if (status == std::future_status::timeout) {
//超时,表示线程还没有结束完
cout << "创建了线程" << endl;
cout << "线程还没有执行完, 超时" << endl;
}
else if (status == std::future_status::ready) {
//表示线程成功返回
cout << "创建了线程" << endl;
cout << "线程成功返回" << endl;
cout << result.get() << endl;
}
else if (status == std::future_status::deferred) {
cout << "没有创建线程" << endl;
//如果 std::future<int> result = std::async(std::launch::deferred, my_thread); //async:异步;
cout << "线程被延迟执行" << endl;
cout << result.get() << endl;
}
cout << "主线程结束 " << endl;
return 0;
}
- Title: C++并行开发11- std__atomic续谈、std__async深入谈
- Author: FengLY
- Created at : 2023-06-18 22:40:09
- Updated at : 2023-06-18 22:59:06
- Link: https://zhouaq.com/2023/06/18/C++并行开发11- std__atomic续谈、std__async深入谈/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments