发布于2026-07-21 阅读(0)
扫一扫,手机访问
说白了,readdir 就是用来读目录内容的函数,C 语言里再常见不过。但问题来了——怎么让它反赌一点?尤其是在目录层级深、文件多的时候,单线程扫一遍,效率低得让人着急。于是多线程就派上了用场。思路其实很简单:把目录拆成若干子目录,每个子目录交给一个线程去执行 readdir,各干各的,互不干扰。下面是一个现成的例子,用 C 语言搭配 POSIX 线程库(pthread)来实现,可以直接上手跑。

#include
#include
#include
#include
#include
#define NUM_THREADS 4
typedef struct {
char *path;
} thread_data_t;
void *scan_directory(void *arg) {
thread_data_t *data = (thread_data_t *)arg;
DIR *dir = opendir(data->path);
struct dirent *entry;
if (dir == NULL) {
perror("opendir");
pthread_exit(NULL);
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
char sub_path[1024];
snprintf(sub_path, sizeof(sub_path), "%s/%s", data->path, entry->d_name);
printf("Scanning directory: %s\n", sub_path);
// 递归扫描子目录
pthread_t thread;
thread_data_t sub_data = {sub_path};
pthread_create(&thread, NULL, scan_directory, &sub_data);
pthread_join(thread, NULL);
}
} else {
printf("Found file: %s\n", entry->d_name);
}
}
closedir(dir);
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s \n", argv[0]);
return 1;
}
pthread_t threads[NUM_THREADS];
thread_data_t thread_data[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
thread_data[i].path = argv[1];
pthread_create(&threads[i], NULL, scan_directory, &thread_data[i]);
}
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
这个程序接受一个目录路径作为命令行参数,然后启动 4 个线程,每个线程都去扫同一个根目录——当然,这里有个小细节:scan_directory 函数里如果遇到子目录,会递归地再创建一个新线程去扫描那个子目录。这样一来,整个目录树就被拆成了多线程并行处理,理论上是能提速的。
不过话说回来,这个示例只是为了演示基本思路,代码里没有处理线程同步和资源竞争问题。如果放在真实项目里,多个线程同时读取同一个目录的文件描述符,或者递归创建线程的数量不受控制,可能会导致预期外的行为。所以,实际应用时一定要加上互斥锁(mutex)或者使用线程池来管理并发,这些都是必须考虑的安全边界。另外,别忘了处理错误情况和内存释放,这里只是抛砖引玉。
下一篇:AppImage是否需要额外依赖
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8