Search code examples
ciothread-safetyreaddirscandir

Is scandir really thread safe?


In the UNIX® System Threads Reference, under the heading of "Thread-safety" is a list of functions are "not guaranteed to be thread-safe on all UNIX systems." The function scandir() is absent from this list, while readdir() appears on the list.

However the glibc source for scandir() clearly appears to call readdir(), not the thread-safe readdir_r(). So was scandir() omitted from the list for some other reason, or is it thread-safe for some reason I am missing?


Solution

  • It appears that POSIX.1-2008 specifies that scandir() is thread-safe, since it is a POSIX.1-2008 function, and not in the list of functions allowed to be non-threadsafe. However, POSIX.1-2008 does not preclude readdir() from being thread-safe, and in the case of glibc, it appears that the readdir() source actually is thread-safe, since it does not return a global struct dirent, rather it returns a glibc-defined member of the DIR type returned in the opendir() call.

    So even though glibc's scandir() calls readdir(), it still appears to be thread-safe.