簡體   English   中英

會有多少個進程和線程?

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

將創建多少個進程和線程?

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

我認為有8個線程和6個進程。

讓我們逐行瀏覽它(格式編輯和注釋添加):

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

所以在我們的程序結束時,我們有 8 個進程和 4 個線程。

如果您不相信我,請嘗試運行此程序並計算打印出“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
}

你也可能意味着thread_create()而不是thread.create()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM