thread

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值