C++线程 基础教程
2016-04-18 18:08
281 查看
#include <iostream> #include <thread> using namespace std; void call(int tid) { cout << "Launched by thread " << tid << endl; } int main() { thread t[10];//启动一组线程 for(int i=0;i<10;i++) { t[i]=thread(call,i); } for(int i=0;i<10;i++) { t[i].join(); } return 0; }
能看到上面的结果中,程序一旦创建一条线程,其运行存在顺序不确定的现象。程序员的任务就是要确保这组线程在访问公共数据时不要出现阻塞。最后几行,所显示的错乱输出,甚至是会输出些混乱的字符。原因在于,程序内的11条线程都在竞争性地使用stdout这个公共资源,要避免上面的问题,可以在代码中使用拦截器(barriers),如std:mutex,以同步(synchronize)的方式来使得一群线程访问公共资源,或者,如果可行的话,为线程们预留下私用的数据结构,避免使用公共资源。
#include <iostream> #include <thread> #include <mutex> using namespace std; std::mutex m; void call(int tid) { m.lock(); cout << "Launched by thread " << tid << endl; m.unlock(); } int main() { thread t[10];//启动一组线程 for(int i=0;i<10;i++) { t[i]=thread(call,i); } for(int i=0;i<10;i++) { t[i].join(); } return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#线程间不能调用剪切板的解决方法
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C#线程同步的三类情景分析
- C#获取进程或线程相关信息的方法
- C#停止线程的方法
- C#子线程更新UI控件的方法实例总结
- C#线程队列用法实例分析
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题