C++ std::this_thread

命名空间std::this_thread提供了一组关于当前线程的函数。

获取当前线程ID:

int main()
{

	cout << this_thread::get_id() << endl;
	thread t([] {cout << this_thread::get_id() << endl; });
	t.detach();
	system("pause");
}

放弃当前线程的时间片,使CPU重新调度以便其它线程执行:

bool g_ready;
void waitReady()
{
	while (!g_ready) {
		this_thread::yield();
	}
	cout << "ok" << endl;
}

int main()
{
	thread t(waitReady);
	t.detach();
	string inputStr;
	while (cin >> inputStr) {
		if (inputStr == "hello"){
			break;
		}
	}
	g_ready = true;
	system("pause");
}

阻塞当前线程一段时间。

int main()
{
	this_thread::sleep_for(chrono::nanoseconds(1000));//阻塞当前线程1000纳秒
	this_thread::sleep_for(chrono::microseconds(1000));//阻塞当前线程1000微妙
	this_thread::sleep_for(chrono::milliseconds(1000));//阻塞当前线程1000毫秒
	this_thread::sleep_for(chrono::seconds(20)+ chrono::minutes(1));//阻塞当前线程1分钟20秒
	this_thread::sleep_for(chrono::hours(1));//阻塞当前线程1小时
	system("pause");
}

阻塞当前线程直到某个时间点。

int main()
{
	chrono::system_clock::time_point until = chrono::system_clock::now();
	until += chrono::seconds(5);
	this_thread::sleep_until(until);//阻塞到5秒之后
	system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值