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 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】