在C++中,使用pthread库创建的线程可以通过pthread_cancel函数来优雅地退出线程。具体步骤如下:
void* thread_func(void* arg) {
while (1) {
// do something
pthread_testcancel();
}
}
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
// 请求取消线程
pthread_cancel(thread);
void cleanup(void* arg) {
// clean up resources
}
void* thread_func(void* arg) {
pthread_cleanup_push(cleanup, NULL);
while (1) {
// do something
pthread_testcancel();
}
pthread_cleanup_pop(1);
}
通过以上步骤,可以实现优雅地退出pthread线程。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:C++中pthread的用法是什么