C++20 std::jthread

C++20 std::jthread

std::jthread 表示 joining thread , 与C++11里面的std::thread不同std::jthread 自动join, 并且可以被外部终止

image-20220806000055090

自动join

std::thread

#include <iostream>
#include <thread>
using namespace std;

int main(int argc, char* argv[])
{
	std::cout << std::boolalpha << std::endl;

	std::thread thr{
		[] { cout << "joinable std::thread<<" << std::endl; }
	};

	std::cout << thr.joinable() << std::endl;
}

执行后会发生:

image-20220806000931700

std::jthread

#include <iostream>
#include <thread>
using namespace std;

int main(int argc, char* argv[])
{
	std::cout << std::boolalpha << std::endl;

	std::jthread thr{
		[] { cout << "joinable std::thread" << std::endl; }
	};

	std::cout << thr.joinable() << std::endl;
}

可以正常运行

外部请求终止

请求终止,不是强制终止, 是否终止由线程本身决定 ,保证终止前能调用析构函数, 遵循RALL

#include <iostream>
#include <thread>
using namespace std;

int main(int argc, char* argv[])
{
	std::jthread nonInterruptable([]()
	{
		int counter{0};
		while (counter < 10)
		{ // 不可以接收终止请求
			std::this_thread::sleep_for(0.2s); // CPP真是越来越好用了
			std::cerr << "non-interruptable thread: " << counter << '\n';
			++counter;
		}
	});

	std::jthread interrupttible(
		[](std::stop_token stoken)
		{
			int counter{0};
			while (counter < 10)
			{
				std::this_thread::sleep_for(0.2s);
				if (stoken.stop_requested()) return; // 可以接收终止请求
				std::cerr << "interruptible" << counter << endl;
				++counter;
			}
		});

	std::this_thread::sleep_for(1s);

	std::cerr << endl;

	nonInterruptable.request_stop(); // 发送终止请求,但是并没有用
	interrupttible.request_stop(); // 发送终止请求,成功让线程终止

	cout << endl;
}

image-20220806002629959

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值