能在上面的基础上再加一个子线程吗
时间: 2024-03-14 13:44:58 浏览: 21
当然可以,在上面的基础上添加一个子线程非常简单,只需要在 `thread_func()` 函数中再创建一个新的线程即可。以下是修改后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
void *thread_func(void *thread_id) {
long tid;
tid = (long) thread_id;
printf("Thread %ld is running\n", tid);
// 创建一个新的线程
pthread_t sub_thread;
int rc;
rc = pthread_create(&sub_thread, NULL, thread_func, (void *) (tid + 1));
if (rc) {
printf("Error: return code from pthread_create() is %d\n", rc);
exit(-1);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for (t = 0; t < NUM_THREADS; t++) {
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, thread_func, (void *) t);
if (rc) {
printf("Error: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
// 等待所有线程结束
for (t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
pthread_exit(NULL);
}
```
在 `thread_func()` 函数中,我们创建了一个新的线程,并且让它的 ID 为当前线程的 ID 加 1。在主函数中,我们使用 `pthread_join()` 函数来等待所有线程结束。需要注意的是,由于我们创建了一个子线程,所以程序会一直运行下去,直到所有的线程都结束。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)