Thursday, July 1, 2010

Makefiles and concurrency

Makefiles offer an option for parallel execution, but there is a stumbling block: it is possible to create race conditions that can lead to corrupt output files if two Makefiles want to make the same target.

For example:

all: a b

        $(MAKE) -f Makefile.a

        $(MAKE) -f Makefile.b
a: x
        echo A
        cat x > a

        echo A makes X!
        sleep 3
        echo 'A' >> x

b: x
        echo B
        cat x > b

        echo B makes X!
        sleep 2
        echo 'B' >> x

When run single-threaded, the file x just contains 'A'. However, in multi-threaded mode, it will contain both lines: 'B' and 'A'. So there is no "stack" of commands to be executed that gets checked for duplicated commands to make the same file. Hence, files that are prerequisites for the parallel parts need to be made first.

No comments: