阅读量:3
要终止一个通过pthread_create创建的线程,您可以使用以下方法之一:
-
线程自动结束:当线程的函数执行完毕时,线程会自动结束。确保您的线程函数在逻辑上有一个明确的退出条件。
-
使用全局标志变量:创建一个全局布尔变量(例如
thread_exit),并在需要终止线程时将其设置为true。在线程的主函数中,定期检查此标志,并在适当的时候使用pthread_exit()函数结束线程。
#include
#include
#include
#include
pthread_mutex_t lock;
pthread_cond_t finish_cond;
int thread_exit = false;
void* thread_function(void *arg) {
while (!thread_exit) {
// 执行线程任务
}
return NULL;
}
int main() {
pthread_t thread;
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&finish_cond, NULL);
pthread_create(&thread, NULL, thread_function, NULL);
// 让线程执行一段时间
sleep(5);
// 终止线程
pthread_mutex_lock(&lock);
thread_exit = true;
pthread_cond_signal(&finish_cond);
pthread_mutex_unlock(&lock);
// 等待线程结束
pthread_join(thread, NULL);
pthread_cond_destroy(&finish_cond);
pthread_mutex_destroy(&lock);
return 0;
}
- 使用
pthread_cancel()函数:pthread_cancel()函数会向线程发送一个取消请求,线程需要检查是否允许被取消。如果允许被取消,线程将执行取消处理代码,然后结束。要使用此方法,您需要在线程函数中实现取消处理代码。
#include
#include
#include
#include
void* thread_function(void *arg) {
while (1) {
// 执行线程任务
}
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
// 让线程执行一段时间
sleep(5);
// 终止线程
pthread_cancel(thread);
// 等待线程结束
pthread_join(thread, NULL);
return 0;
}
请注意,使用pthread_cancel()可能导致资源泄漏,因为线程可能没有机会释放其占有的资源。因此,在使用pthread_cancel()之前,请确保线程能够安全地结束。在许多情况下,使用全局标志变量或自动结束的方法更为可靠。
以上就是关于“如何终止pthread_create创建的线程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm