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;
}