c++thread里暂停线程_如何终止或停止C ++中的分离线程?

在C++中,没有直接的方法来终止或停止一个分离线程。最佳实践是让线程自行退出。在示例中,可以通过在线程函数中添加一个布尔标志和互斥锁来实现。主线程在结束前设置标志并等待线程检查标志后退出,以解决可能的内存泄漏问题。
摘要由CSDN通过智能技术生成

I am interested in terminating/stopping/killing a detached thread in c++. How can this be done?

void myThread()

{

int loop = 0;

while(true)

{

std::this_thread::sleep_for(std::chrono::seconds(5));

++loop;

}

}

void testThread()

{

std::thread globalThread(myThread);

globalThread.detach();

}

int main(void)

{

testThread();

for(unsigned int i=0; i < 1000; i++)

{

cout << "i = " << i << endl;

}

return 0;

}

The reason why I'd like to "stop"/"terminate" the globalThread() is because valgrind lists that this is a "possibly lost" type of memory leak (152 bytes). What is the b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值