阅读量:3
在C语言中,一旦通过pthread_create成功创建了一个线程,就不能直接取消(取消线程的执行)。但是,你可以使用以下方法来间接地终止线程:
- 使用条件变量和互斥锁来通知线程退出。线程会定期检查一个共享的条件变量,如果该条件满足,线程就会自动退出。为了实现这一点,你需要在线程函数中使用
pthread_mutex_lock和pthread_mutex_unlock来保护共享数据,并使用pthread_cond_wait来等待条件变量。当需要终止线程时,可以设置共享数据并唤醒线程。
#include
#include
#include
#include
pthread_mutex_t lock;
pthread_cond_t finish_cond;
int done = 0;
void* thread_function(void *arg) {
while (1) {
pthread_mutex_lock(&lock);
if (done) {
pthread_mutex_unlock(&lock);
return NULL;
}
pthread_mutex_unlock(&lock);
// 执行任务
printf("Thread is working...\n");
sleep(1);
}
}
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);
done = 1;
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) {
// 执行任务
printf("Thread is working...\n");
sleep(1);
}
}
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_create创建的线程吗”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm