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<iostream>
#include<thread>
#include<chrono>
#include<Windows.h>

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值