Search This Blog

Thursday, November 11, 2010

How to use fork() in unix? Why not something of the form fork(pointerToFunctionToRun)?

Programmer Question

I am having some trouble understanding how to use Unix's fork(). I am used to, when in need of parallelization, spawining threads in my application. It's always something of the form



CreateNewThread(MyFunctionToRun());

void myFunctionToRun() { ... }


Now, when learning about Unix's fork(), I was given examples of the form:



fork();
printf("%d\n", 123);


in which the code after the fork is "split up". I can't understand how fork() can be useful. Why doesn't fork() have a similar syntax to the above CreateNewThread(), where you pass it the address of a function you want to run?



To accomplish something similar to CreateNewThread(), I'd have to be creative and do something like



//pseudo code
id = fork();

if (id == 0) { //im the child
FunctionToRun();
} else { //im the parent
wait();
}


Maybe the problem is that I am so used to spawning threads the .NET way that I can't think clearly about this. What am I missing here? What are the advantages of fork() over CreateNewThread()?



PS: I know fork() will spawn a new process, while CreateNewThread() will spawn a new thread.



Thanks



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails