千万注意线程不要比主线程晚结束,主线程一旦结束,对象将被销毁

std:thread 代表了一个线程对象

this_thread:是一个命名空间,对当前调用者线程进行操作

如果把可调用对象作为参数传递给子线程的构造函数,则把该调用对象复制一份给子线程

如果需要传递可调用对象的左值引用给子线程,采用std::ref()产生对象的引用,再把引用值传进去给子线程

线程直接接受操作系统调度,一个进程所能创建的线程数目和一个操作系统所能创建的总的线程数据等都由运行时操作系统限定

std::thread中主要有三类函数:构造函数,成员函数,静态成员函数

类成员函数:

get_id():获取线程的ID,不指明具体对象时,获取的是当前正在运行的线程的ID,返回一个类型为std:🧵:id的对象

std:🧵🆔表示线程ID,定义了在运行时操作系统内唯一能标识该线程的标识符,同时其值还能指示所标识的线程状态

上述两个可以配套使用

//获取线程ID
thread::id main_thread_id = this_thread::get_id();
void is_main_thread( )
{
	if (main_thread_id == std::this_thread::get_id())
	{
		cout << "this is main thread" << endl;
	}
	else
	{
		cout << "it is not the main thread" << endl;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	is_main_thread();
	
	thread th(is_main_thread);
	cout << "线程ID"<<th.get_id() << endl;
	cout <<"主线程ID"<< this_thread::get_id() << endl;
	cout << get_id() << endl;
	th.join();
	return 0;
}

joinable():检查thread对象是否有一个活动的可行线程,检查线程是否可被join()

//判断thread对象是否有一个活动的可行线程

void mythread()
{
	//sleep_for(chrono::seconds(2));
}
int _tmain(int argc, _TCHAR* argv[])
{
	thread foo;//缺省构造函数,线程不执行
	thread bar(mythread);
	cout << "joinable after construction:\n" << boolalpha;
	cout << "foo:" << foo.joinable() << '\n';
	cout << "bar:" << bar.joinable() << '\n';
	if (foo.joinable())
	{
		foo.join();
	}
	if (bar.joinable())
	{
		bar.join();
	}
	cout << "joinable after joining:\n" << boolalpha;  //boolalpha把数字变成true或false
	cout << "foo:" << foo.joinable() << '\n';
	cout << "bar:" << bar.joinable() << '\n';
	return 0;
}

join():调用该函数会阻塞调用者所在的线程,在哪里使用就会在哪停下来等待,直到join的thread对象标识的线程结束

sleep_for()函数:为该线程休眠某个指定时间片段,该线程才被重新唤醒,不过由于线程调度等原因,实际休眠时间会更长

sleep_until()函数: 该线程休眠至某个指定时刻,该线程才被重新唤醒

//创建线程和加入

void pause_thread(int n)
{
	sleep_for(chrono::seconds(n));
	cout << "pause of" << n << "seconds ended\n" << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<thread> vec;
	cout << "spawning 3 threads ...\n";
	/*thread t1(pause_thread, 1);
	thread t2(pause_thread, 2);
	thread t3(pause_thread, 3);*/  //此处自行选择其中一种方式进行初始化
	for (int i = 0; i < 3; i++)
	{
		vec.push_back(thread(pause_thread, 1));
	}
	cout << "done spawning threads,now waiting for them to join:\n";
	//t1.join();
	//t2.join();
	//t3.join();
	for_each(vec.begin(), vec.end(), mem_fn(&std::thread::join));
	cout << "all threas joined\n";
	return 0;
}

yield函数:将调用者线程跳出运行状态,重新交给操作系统进行调度,即当前线程放弃执行,操作系统调度另一线程继续执行

静态成员函数:

hard_concurrency:返回当前计算机最大的硬件并发线程数目

posted on 2018-09-13 21:52  泰坦妮克号  阅读(365)  评论(0)    收藏  举报