stl-thread-001
来源:互联网 发布:律师知乎 编辑:程序博客网 时间:2024/06/05 06:04
介绍c++11引入的标准线程类thread,属于入门系列。
这是第一篇,转自c++标准库:开2个子线程运行,并取得结果;
#include<future>#include<thread>#include<iostream>#include<random>#include<chrono>#include<exception>using std::cout;using std::endl;void doSomeThing(char c){ std::default_random_engine engine(c); std::uniform_int_distribution<int> distribute(200, 1000); for (int i = 0; i < 10;i++) { std::this_thread::sleep_for(std::chrono::milliseconds(distribute(engine))); cout.put(c).flush(); }}int main(){ cout << "2 task starting..." << endl; std::future<void> f1 = std::async([]{doSomeThing('-'); }); std::future<void> f2 = std::async([]{doSomeThing('+'); }); if (f1.wait_for(std::chrono::seconds(0)) != std::future_status::deferred || f2.wait_for(std::chrono::seconds(0)) != std::future_status::deferred) { while (f1.wait_for(std::chrono::seconds(0)) != std::future_status::ready && f2.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { std::this_thread::yield(); } } cout << endl; try { f1.get();//取得结果,每一个future的get()只能执行一次; f2.get();//取得结果,每一个future的get()只能执行一次; } catch (const std::exception& e) { cout << "exception:" << e.what(); } cout << "\ndone!" << endl; getchar(); getchar(); return 0;}
0 0
- stl-thread-001
- STL--thread
- stl-thread-002
- stl-thread-003
- STL线程 std::thread
- stl,boost,thread,IOCP,socket
- SGI STL (3) :: Thread Safe
- About the thread safety on STL
- STL(VC6) Good Q&A(五):Are Containers Thread Safe?
- STL(VC6) Good Q&A(五):Are Containers Thread Safe?
- STL(VC6) Good Q&A(五):Are Containers Thread Safe?
- STL(VC6) Good Q&A(五):Are Containers Thread Safe?
- STL(VC6) Good Q&A(五):Are Containers Thread Safe?
- STL(VC6) Good Q&A(五):Are Containers Thread Safe?
- STL(VC6) Good Q&A(五):Are Containers Thread Safe?
- Thread
- thread
- Thread
- iOS学习笔记:Object-C基础语法(OC介绍与Foundation初步)
- 重置QComboBox项的时候产生currentIndexChanged信号
- widgets之switch和ToggleButton
- c++ 队列Queue的实现 - 练习题
- poj3270cow sorting 置换群裸题
- stl-thread-001
- Lua_第 21 章 操作系统库
- .NET执行sql文件
- Dev之GridControl详解
- codeforces_598D. Igor In the Museum(dfs)
- leetcode——9——Palindrome Number
- cocos2D-X源码分析之从cocos2D-X学习OpenGL(2)----QUAD_COMMAND
- 让Visual Studio 也支持JS代码折叠 [ Visual Studio | #region | #endregion ]
- C# Winform 程序打包部署