补全cancelThread函数,使用pthread_cancel函数终止指定的线程,thread为线程要被取消的线程ID号,调用成功返回0,否则返回-1。#include <stdio.h> #include <pthread.h> /************************ * 参数thread: 需要等待结束的线程ID号 * 返回值: 等待成功返回0,失败返回-1 * 提示: 忽略线程返回值 *************************/ int cancelThread(pthread_t thread) { int ret = -1; /********** BEGIN **********/ /********** END **********/ return ret; }
时间: 2023-08-22 10:08:14 浏览: 48
int cancelThread(pthread_t thread) {
int ret = -1;
if(pthread_cancel(thread) == 0) {
ret = 0;
}
return ret;
}
注解:pthread_cancel函数用于终止指定的线程,第一个参数为线程ID号。如果调用成功,pthread_cancel返回0,否则返回错误码。
相关问题
补全cancelThread函数,使用pthread_cancel函数终止指定的线程,thread为线程要被取消的线程ID号,调用成功返回0,否则返回-1
下面是补全的代码:
```c
int cancelThread(pthread_t thread) {
int ret = pthread_cancel(thread);
if (ret != 0) {
perror("pthread_cancel");
return -1;
}
return 0;
}
```
该函数接收一个线程ID号,使用pthread_cancel函数终止指定的线程。如果调用成功返回0,否则返回-1。在函数内部对返回值进行了判断,如果返回值不为0则输出错误信息,并返回-1。
补全waitThread函数,使用pthread_join函数挂起当前线程,等待指定线程结束,thread为要等待的线程ID号,waitThread函数等待线程成功返回0,失败返回-1
下面是补全后的waitThread函数代码:
```
int waitThread(pthread_t thread) {
int ret = pthread_join(thread, NULL);
if (ret != 0) {
return -1;
}
return 0;
}
```
在该函数中,我们使用pthread_join函数来挂起当前线程,等待指定线程结束。如果成功等待到了指定线程的结束,pthread_join函数将返回0,我们将其返回值作为waitThread函数的返回值。如果等待失败,pthread_join函数将返回一个非零值,我们将其转换为-1返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)