简体   繁体   English

nftw线程安全

[英]nftw thread safe

Is there any thread safe implementation of nftw() in C/C++? 在C / C ++中是否有任何线程安全的nftw()实现? In the documentation it says 在文档中说

"The nftw() function need not be thread-safe." “nftw()函数不需要是线程安全的。”

I'm going to use nftw for a recursive delete function to walk through the directory structure in a multi threaded application. 我将使用nftw作为递归删除函数来遍历多线程应用程序中的目录结构。

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. 通常,您需要在解锁之前复制结果,但是nftw不会产生任何在返回后需要复制的结果。 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. nftw一个选项使它成为它走过的每个目录的chdir 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. 在具有openat和相关接口的POSIX 2008系统上,实现你自己的等效nftw而没有任何chdir用法或路径名长度限制是非常简单的,所以你可能最好只编写自己的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM