c++ 可以检测线程是否销毁的thread_guard

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 1e2, Q = N;
using ll = long long;
int n, q;
ll a[N];
int sta[N];
struct q_t{
	int l, r;
}que[Q];
ll res[N];
ll query(int l, int r){
	ll sum = 0;
	for(ll i = l ;i <= r; ++i) sum += a[i];
	return sum;
}
void make_query(int id){
	res[id] = query(que[id].l, que[id].r);
	std :: this_thread :: sleep_for(chrono :: milliseconds(50));
}
struct thread_guard{
	thread thr;
	bool alive;
	template<typename Ftp>
	thread_guard(const Ftp& func_){
		static auto func = func_;
		static auto func1 = [&](bool& myvis){
			func();
			myvis = false;
		};
		alive = true;
		thr = thread(func1, std::ref(alive));
	}
	~thread_guard(){
		if(thr.joinable()) thr.join();
	}
	bool is_alive()const{
		return alive;
	}
};
int main(){
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n >> q;
	for(int i = 1; i <= n; ++i){
		cin >> a[i];
	}
	for(int i = 1; i <= q; ++i){
		cin >>que[i].l >> que[i].r;
	}
	int id = 1;
	thread_guard thr( std::move(bind(make_query, 1)));
	cout << thr.is_alive() << endl;
	std :: this_thread :: sleep_for(chrono :: milliseconds(150));
	cout << thr.is_alive() << endl;
	return 0;
}

作者:cdsidi

出处:https://www.cnblogs.com/cdsidi/p/17112508.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   CDsidi  阅读(132)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up light_mode palette
选择主题