While fragment X of code is executed, fragment Y should not be executed and when Y is executed X should not be executed. Instead X and Y should be paused if another one is currently executed.
However any number of processes or threads are allowed to concurrently execute code X.
What about executing more than one Y in parallel? It should either also pause until another instance of Y is executed or die with an error "Cannot execute more than one Y in parallel".
Can this be implemented with Unix advisory file locks? I think I should write the number of currently executed X into the file (similar to reference counting). Or maybe I need two files: one for storing the number of concurrent processes executing X and the other for locking the first one? Now let's try to construct the algorithm.
Note that I write in Python.