pthread_cancel()的使用示例
时间: 2024-02-17 17:00:19 浏览: 19
下面是一个使用pthread_cancel()函数的示例代码:
```
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *thread_func(void *arg) {
int i = 0;
while (1) {
printf("Thread is running: %d\n", i);
i++;
sleep(1);
}
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int ret = pthread_create(&thread, NULL, thread_func, NULL);
if (ret != 0) {
printf("Create thread failed.\n");
return -1;
}
sleep(5);
ret = pthread_cancel(thread);
if (ret != 0) {
printf("Cancel thread failed.\n");
return -1;
}
pthread_join(thread, NULL);
return 0;
}
```
该示例代码创建了一个线程,并在其中使用while(1)循环打印信息。在主线程中,等待5秒钟后,调用pthread_cancel()函数取消线程。线程被取消后,使用pthread_join()函数等待线程退出。
需要注意的是,被取消的线程需要显式地处理取消请求,否则将不会响应取消请求。在上述示例代码中,线程没有进行取消请求的处理,因此可能会导致一些资源无法释放,从而导致内存泄漏等问题。