views:

424

answers:

5

I have a C shell script that does something like this:

#!/bin/csh
gcc example.c -o ex
gcc combine.c -o combine
ex file1 r1     <-- 1
ex file2 r2     <-- 2
ex file3 r3     <-- 3
#... many more like the above
combine r1 r2 r3 final
\rm r1 r2 r3

Is there some way I can make lines 1, 2 and 3 run in parallel instead of one after the another?

+5  A: 

Convert this into a Makefile with proper dependencies. Then you can use make -j to have Make run everything possible in parallel.

Note that all the indents in a Makefile must be TABs. TAB shows Make where the commands to run are.

Also note that this Makefile is now using GNU Make extensions (the wildcard and subst functions).

It might look like this:

export PATH := .:${PATH}

FILES=$(wildcard file*)
RFILES=$(subst file,r,${FILES})

final: combine ${RFILES}
    combine ${RFILES} final
    rm ${RFILES}

ex: example.c

combine: combine.c

r%: file% ex
    ex $< $@
Zan Lynx
Your `-l combine` should be `-o combine`
SiegeX
Would you put the `final` rule first to make it the default?
glenn jackman
What was I thinking? Fixed.
Zan Lynx
I like your answer but I just realized his question states more than just 3 possible files and this doesn't seem to scale all that well.
SiegeX
@SiegeX: It is very possible to do wildcards in a Makefile. Then it could process every file* in the directory.
Zan Lynx
Beware the habit of running "make -j" without the integer argument. It will keep spawning as fast as it can. This can cripple a machine during a build with a lot of source files.A better habit is something like "make -j8"
Mark Borgerding
+2  A: 

In bash I would do;

ex file1 r1  &
ex file2 r2  &
ex file3 r3  &
wait
... continue with script...

and spawn them out to run in parallel. You can check out this SO thread for another example.

qor72
That wait will only wait for the last ex. You need to use just wait by itself, no argument.
Zan Lynx
Good catch! So edited.
qor72
+3  A: 
#!/bin/bash

gcc example.c -o ex
gcc combine.c -o combine

# Call 'ex' 3 times in "parallel"
for i in {1..3}; do
  ex file${i} r${i} &
done

#Wait for all background processes to finish
wait

# Combine & remove
combine r1 r2 r3 final
rm r1 r2 r3

I slightly altered the code to use brace expansion {1..3} rather than hard code the numbers since I just realized you said there are many more files than just 3. Brace expansion makes scaling to larger numbers trivial by replacing the '3' inside the braces to whatever number you need.

SiegeX
A: 
oraz
A: 

GNU Parallel would make it pretty like:

seq 1 3 | parallel ex file{} r{}

Depending on how 'ex' and 'combine' work you can even do:

seq 1 3 | parallel ex file{} | combine

Learn more about GNU Parallel by watching http://www.youtube.com/watch?v=LlXDtd_pRaY

Ole Tange