My question is an extension to the question previously asked here.
I need to create a directory tree which may or may not exist earlier and moreover multiple threads can try to create such directory structure. The question cited solves the problem for single threads. Is that function thread safe or are there any specific ways of doing it. I am using C and OS is Ubuntu.
In libc, mkdir can set the error value
EEXISTwhich means ‘that directory already exists’. Thanks Jonathan Leffler “errno is thread-safe as long as you tell the compilation to make things thread-safe”.Creating directories is monotonic – you are always adding new ones, not removing them. So you can create a directory tree (attempting to create each directory at each level) and if some other thread got there first, it’s not a problem, keep going.
If I were you, I would have each thread create its entire path recursively, ignoring errors. When it is complete building its path, it should then test whether the directory exists. If it does not exist, that is a problem (as the sequence of
mkdiroperations that you used to create the required path will be synchronous within the thread). If it does exist, congratulations.