0

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.

Community
  • 1
  • 1
Aman Deep Gautam
  • 8,091
  • 21
  • 74
  • 130

2 Answers2

1

In libc, mkdir can set the error value EEXIST which 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 mkdir operations that you used to create the required path will be synchronous within the thread). If it does exist, congratulations.

Community
  • 1
  • 1
Joe
  • 46,419
  • 33
  • 155
  • 245
0

The O/S will take care of multiple threads trying to create the same directory at 'the same time'. At most one will succeed; the other's will fail, probably with EISDIR (or maybe EEXIST) as the error.

The code in the cross-referenced question won't recover from the EISDIR error. However, if you spot that errno is the relevant error when you check the return code, you can decide to try again.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278