linux C:多进程嵌套多线程的例子
时间: 2023-07-22 09:39:01 浏览: 119
以下是一个简单的多进程嵌套多线程的例子,其中父进程创建两个子进程,每个子进程再创建两个线程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void *thread_func(void *arg) {
int tid = *(int *)arg;
printf("Thread %d is running in Process %d\n", tid, getpid());
return NULL;
}
int main() {
pid_t pid;
int i, j, k;
for (i = 0; i < 2; i++) {
pid = fork();
if (pid < 0) {
perror("fork error");
exit(EXIT_FAILURE);
} else if (pid == 0) {
printf("Child Process %d is running\n", getpid());
for (j = 0; j < 2; j++) {
pthread_t tid;
int ret;
int *arg = (int *)malloc(sizeof(int));
*arg = j;
ret = pthread_create(&tid, NULL, thread_func, arg);
if (ret != 0) {
perror("pthread_create error");
exit(EXIT_FAILURE);
}
}
for (k = 0; k < 2; k++) {
pthread_join(tid, NULL);
}
printf("Child Process %d is exiting\n", getpid());
exit(EXIT_SUCCESS);
}
}
for (i = 0; i < 2; i++) {
wait(NULL);
}
printf("Parent Process %d is exiting\n", getpid());
exit(EXIT_SUCCESS);
}
```
在这个例子中,父进程创建两个子进程,每个子进程再创建两个线程。每个线程打印出它所属的进程和线程编号。父进程在两个子进程都结束后退出。运行程序,可以看到输出结果类似于:
```
Child Process 13063 is running
Thread 0 is running in Process 13063
Thread 1 is running in Process 13063
Child Process 13064 is running
Thread 0 is running in Process 13064
Thread 1 is running in Process 13064
Child Process 13063 is exiting
Thread 0 is running in Process 13064
Thread 1 is running in Process 13064
Child Process 13064 is exiting
Parent Process 13062 is exiting
```
可以看到,每个进程都创建了两个线程,并且线程运行的顺序是不确定的。
阅读全文
相关推荐















