thread
来源:互联网 发布:形容数据整齐的词语 编辑:程序博客网 时间:2024/06/03 20:19
thread是c++标准程序库中的一个头文件,表示线程类,位于std空间中。thread对象初始化给出线程执行函数,线程对象构造完成后即可运行。在默认情况下,c++11中的子线程必须加入到主线程运行,即在主线程(main函数)中调用join函数,这样是为了避免主线程运行完毕后子线程还没有运行完成。
每个程序都至少有一个thread,即main()
作为起始thread,而每个新加入的thread都是在已有的thread某个执行点上生成分支。
// ConsoleApplication78.cpp : 定义控制台应用程序的入口点。/* thread*/#include "stdafx.h"#include<thread>#include<iostream>#include<string>//#include <boost/thread/scoped_thread.hpp>using namespace std;class scoped_thread{thread t;public:explicit scoped_thread(thread _t){//检查子线程是否可加入主线程t =move(_t);if (!t.joinable()){cout <<"子线程不能加入到主线程中" << endl;throw logic_error("not thread");}cout <<"call scoped_thread (thread)"<< endl;}scoped_thread(){cout <<"call scoped_thread ()" << endl;}~scoped_thread(){//对象销毁时,将子线程加入到主线程中cout <<"对象销毁" << endl;t.join();}scoped_thread(scoped_thread const&) = delete;scoped_thread& operator=(scoped_thread const&) = delete;};void do_something(int& i){cout << i << " ";++i;}struct func{int &i;func(int &_i):i(_i){//cout <<"call func()" << endl;};void operator()(){//cout <<"call ()" << endl;for (unsigned j = 0; j < 20; j++){do_something(i);}}};void do_something_in_current_thread(){}//void do_something_with_current_thread(thread& th)//{// th.join();//}//主线程int _tmain(int argc, _TCHAR* argv[]){int some_local_state = 1;//子线程--将未命名线程对象直接传递给scoped_thread//thread类不允许拷贝scoped_thread t(thread{func(some_local_state) });/*匿名类(仿函数)生成thread类可能会产生歧义*///scoped_thread t(thread(func(some_local_state) ));//在主线程对象t销毁时将子线程加入主线程mian中,do_something_in_current_thread();system("pause");return 0;}
0 0
- Thread
- thread
- Thread
- Thread
- thread
- thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Knowledge of SFP Auto-Negotiation
- label标签的for属性规定 与哪个表单元素绑定(转载)
- bzoj 1299 巧克力棒 博弈论
- 个人学习常识笔记
- 页面快速定位,根据得到的ID,定位到ID对应的元素
- thread
- web.xml配置之<context-param>详解
- TensorFlow学习笔记1----介绍
- python学习记录
- Action/Service/DAO简介
- 训练样本制作--Annotating Object Instances with a Polygon-RNN
- Linux命令
- sim开机APDU命令流程
- 无痛学会各种 2 的 Vue2+Vuex2+Webpack2 前后端同构渲染