tags:

views:

68

answers:

3

Hi
I need to use shared memory and fork to do this:
Multipling random 512x512 matrixes using 4 processes and shared memory.
I know how to fork one child but
How can I fork 4 processes that do 1/4 of work?

Thanks

A: 

Why don't you just fork three times in a row?

Jens Gustedt
You also need to somehow communicate to the forked processes which set of processing they need to do. While not rocket science, Borealid's answer gives a nice, elegant method.
Michael Burr
@Micheal: sure, just thought that he could figure that out by himself or rephrase his question in a more precise manner. Guess the `homework` tag is missing, no?
Jens Gustedt
+3  A: 
ct = 0;
while (ct < 3 && fork() == 0) {
    ct++;
}

ct will tell you which thread you are. You should probably check for a return of -1 from fork(), though.

Borealid
The thing I don't Understand is 3! Why always we fork one less than number of required processes? Why 3 and not 4?
Snigger
The first one is 0. The second one is 1. The third one is 2. When 2 forks, that one (the fourth) becomes 3, and short-circuits the while statement to not fork again.
Borealid
@Snigger: one process you already have from the start, so you only have to launch the missing 3 other ones.
Jens Gustedt
So I should do 1/4 of work in the original process? and 3/4 in childs?
Snigger
@Snigger: after forking, there's no real distinction between the original and the children. Just do 1/4 the work in each of your four processes, and then (probably) combine the results in one of them.
Borealid
Thank you very much
Snigger
+1  A: 

How about this: Read the chapter in your textbook again, ask your classmates for the notes you missed, attack your TA while he or she is sneaking out of his office, then ask your professor during their office hours!

John