Click to See Complete Forum and Search --> : Linux Multithreading :: C++


kuphryn
October 6th, 2002, 04:27 PM
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?


// 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?



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

cup
October 7th, 2002, 03:12 AM
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.

kuphryn
October 7th, 2002, 09:32 AM
Okay. Thanks.

Kuphryn