Do not run custom targets in parallel

I have a custom function that creates a custom target with a custom command. This custom command uses a common file (changes it and restores it).

Now, there is a race condition. If two of those targets run at the same time the file is modified by both target resulting in wrong outputs.
I cannot make them depend on each other, because they should not know of each other.
I cannot copy the file, it needs to stay at the same location.

Tests have a property RUN_SERIAL which would be great but well, its a target not a test. There is also file(LOCK) but this cannot be used since it would run in different processes which it does not support according to documentation.

Do you know a way of doing this?

Run the build in serial: ninja -j1 or make -j1.

Alternatively, change your custom commands to not use a common file, or to establish a lock on it so that only one modifies it at a time.

There are other ways of locking files. It’s a very common problem for daemons. I’d suggest taking a look at how other software locks files.

Sure, this is possible, but it is hard to get this platform independent.