CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2002
    Posts
    5,757

    Linux Multithreading :: C++

    Hi.

    I have a simple questions for Linux programmers. I am a C++ programmers, but I have no experience working with multithreaded programming in Linux. I would like to understand fork().

    For example, how many processes including main process does the following code produces?

    Code:
    // p -> one child process
    
    int main()
    {
    fork();  // p 
    fork(); // p 
    fork(); // p
    fork(); // p
    
    return 0;
    The code above will spawn a total of five processes including main. Is that accurate?

    Secondly, I would like to know let say when you spawn a process using fork() I know the child-process will execute at that very instance and all the code after it. What if you spawn one child-process after another, does the total number of processes increases exponantially?

    Lastly, if you spawn a child-process inside an if statement, will the child-process execute code outside of the if statement?

    Code:
    int main()
    {
    fork();
    
    // If child-process, then execute.
    // fork() returns 0 for the child-process.
    
    if (!forker()_
    {
    ...
    }
    
    cout << "will the child-process execute this line?";
    
    return 0;
    }
    Thanks,
    Kuphryn

  2. #2
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    Using fork () is actually multi-processing: not multi threading. The difference is that a separate process is created and the scheduling is done by the operating system. With multi-threading, the threads are created within the same process. The scheduling is done within that process.

    Having said that, on some implementations, there is no difference as the threads are created as separate processes.

    Answers to your questions

    1) As you said - 5.
    2) Yes it increases exponentially if the child processes breed more than one child each.
    3) Yes.
    Succinct is verbose for terse

  3. #3
    Join Date
    Feb 2002
    Posts
    5,757
    Okay. Thanks.

    Kuphryn

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured