Question

Is there any thread safe implementation of nftw() in C/C++? In the documentation it says

"The nftw() function need not be thread-safe."

I'm going to use nftw for a recursive delete function to walk through the directory structure in a multi threaded application.

Was it helpful?

Solution

One trivial way to make a non-thread-safe function thread-safe is to wrap it in a function that obtains a lock before calling it, and always call it through this wrapper. In general you would need to copy out the results before unlocking, but nftw does not yield any results that would need to be copied after it returns. A few caveats though:

  1. This will of course prevent all parallelism when multiple threads want to use the interface.

  2. One option to nftw makes it chdir to each directory it walks. This is a very bad thing for a multi-threaded app (since the current directory is shared by all threads), so you should avoid using this option.

On POSIX 2008 systems with the openat and related interfaces, it's pretty trivial to implement your own equivalent of nftw without any chdir usage or pathname length limitations, so you might be better off just writing your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top