LAMBDA表达式与线程及线程等待和获取线程ID

本代码主要是使用LAMBDA表达式与线程的一起使用,还有线程的几个方法的测试:

如:获取线程的ID、线程等待,线程等待的几种方法如下:

this_thread::sleep_for(chrono::seconds(3));//线程等待 3 秒
this_thread::yield();//让CPU先执行其他线程,空闲时再执行些线程
this_thread::sleep_until();//到某个时刻到来之前一直等待,定时等待。

测试代码如下:

/*
C++中创建多线程,建议使用LAMBDA表达式
下面几个参数在 迅雷 的定时下载中都有体现 如空间下载、定时下载.......
this_thread::sleep_for()	//等待多少秒后执行。
this_thread::yield();		//CPU空闭了才执行行
this_thread::sleep_unitl();	//等到某个时间点时才执行
this_thread::get_id()	//获取线程ID
*/
#include
#include
#include
#include

using namespace std;

//线程等待与获取线程 ID
void main4C()
{
	thread th1([](){
		
		this_thread::sleep_for(chrono::seconds(3));	//线程等待 3 秒
		//this_thread::yield();	//让CPU先执行其他线程,空闲时再执行些线程
		//this_thread::sleep_until();	//到某个时刻到来之前一直等待,定时等待。
		cout << this_thread::get_id() << endl;		//获取线程的 ID
	});

	thread th2([](){
		this_thread::sleep_for(chrono::seconds(10));	//线程等待 10 秒
		cout << this_thread::get_id() << endl;
	});

	th1.join();
	th2.join();

	cin.get();
}

void main4b()
{	
	thread th1([](){MessageBoxA(0, "1", "2", 0); });
	thread th2([](){MessageBoxA(0, "1", "2", 0); });
	th1.join();
	th2.join();

	cin.get();
}

void main4a()
{
	auto fun = [](){MessageBoxA(0, "1", "2", 0); };
	thread th1(fun);
	thread th2(fun);
	th1.join();
	th2.join();

	cin.get();
}


你可能感兴趣的:(C++,C++线程)