简体   繁体   English

会有多少个进程和线程?

[英]How many processes and threads will there be?

How many processes and threads will be created?将创建多少个进程和线程?

pid_t pid;
pid = fork();
if (pid == 0)
{
/* child process */
fork();
thread.create(...);
}
else
{
/* parent process */
fork();
thread.create(...);
}
fork();

I think there are 8 threads and 6 processes.我认为有8个线程和6个进程。

Let's walk through it line by line (format edits and comments added):让我们逐行浏览它(格式编辑和注释添加):

pid_t pid;
pid = fork(); //Parent spawns child 1
if (pid == 0)
{
  /* child process */
  fork(); //Child 1 spawns child 2
  thread.create(...); //Child 1 and child 2 spawn threads 1 and 2 respectively
}
else
{
  /* parent process */
  fork(); //Parent spawns child 3
  thread.create(...); //Parent and child 3 spawn threads 3 and 4 respectively
}
fork(); //Parent and children 1,2, and 3 spawn children 4, 5, 6, and 7

So at the end of our program we have 8 processes and 4 threads.所以在我们的程序结束时,我们有 8 个进程和 4 个线程。

If you don't believe me try running this program and count the number of times "Thread" and "Process" are printed out.如果您不相信我,请尝试运行此程序并计算打印出“Thread”和“Process”的次数。

int main(){
  if(fork()){
    fork();
    printf("Thread\n"); //Simulate spawning a thread that prints "Thread"
  }
  else{
    fork();
    printf("Thread\n"); //Simulate spawning a thread that prints "Thread"
  }
  fork();
  printf("Process\n"); //Have each forked process sound off
}

You also might mean thread_create() instead of thread.create()你也可能意味着thread_create()而不是thread.create()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM