0

我的问题是对先前在此处提出的问题的扩展。

我需要创建一个目录树,它可能更早存在也可能不存在,而且多个线程可以尝试创建这样的目录结构。引用的问题解决了单线程的问题。该函数是线程安全的还是有任何特定的方法可以做到这一点。我正在使用C,操作系统是 Ubuntu。

4

2 回答 2

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.

于 2012-07-02T22:06:16.517 回答
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.

于 2012-07-02T22:07:34.850 回答