【发布时间】:2016-10-19 15:46:18
【问题描述】:
我有以下代码,它使用fork() 创建定义数量的子线程:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#define NUM_THREADS 4
int main()
{
int i;
pid_t pid;
for(i = 0; i < NUM_THREADS; i++){ //Do this equal to the number of threads
pid = fork();//Use this to avoid multiple forking
if(pid == 0){ //If it's a child process
printf("Hello World! Greetings from PID: %ld! :D\n", (long)getpid()); //getpid returns the pid of the process
exit(0); //Exit the process
}else if(pid == -1){
printf("Oh no! Could not fork! :( Exiting!\n");
return 0;
}
}
int status;
for(i = 0; i < NUM_THREADS; i++){
wait(&status);//wait until all the children processes have finished.
}
printf("All done! I am the parent process! My PID is: %ld if you were curious! \n", (long)getpid());
return 0;
}
这是作为示例提供给我们的。 它的输出是这样的:
世界你好!来自PID的问候:118358! :D
你好世界!来自PID的问候:118359! :D
你好世界!来自PID的问候:118360! :D
你好世界!来自PID的问候:118362! :D
我想做的是让父进程创建一个子进程,然后再创建一个子进程,而不是让 1 个父进程和许多子进程,以此类推,以定义线程数。我该怎么做?
【问题讨论】:
-
您是否尝试过自己编写代码?你到底有什么问题?