int pthread_cancel(pthread_t thread);
时间: 2023-08-24 21:05:43 浏览: 48
`pthread_cancel`函数是一个线程取消函数,用于请求取消指定的线程。它接受一个`pthread_t`类型的参数`thread`,用于指定要取消的线程。
函数原型如下:
```c
int pthread_cancel(pthread_t thread);
```
使用示例:
```c
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
while (1) {
printf("线程执行中...\n");
sleep(1);
}
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
sleep(3);
int ret = pthread_cancel(tid); // 请求取消线程
if (ret == 0) {
printf("线程取消成功\n");
} else {
printf("线程取消失败\n");
}
pthread_join(tid, NULL); // 等待线程结束
return 0;
}
```
在上述示例中,我们创建了一个子线程并在其中使用一个无限循环来模拟线程的执行。在主线程中,通过调用`pthread_cancel`函数请求取消子线程。然后,使用`pthread_join`函数等待子线程结束。
需要注意的是,`pthread_cancel`函数只是向指定线程发送一个取消请求,实际上是否可以成功取消线程取决于线程本身对取消请求的处理。子线程可以通过设置取消状态和处理取消请求的回调函数来决定是否响应取消请求。在示例中,如果子线程在被取消前等待了3秒,则可以成功取消线程,并在主线程中得到相应的提示。