readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要将 readdir 与多线程结合,您可以使用 POSIX 线程(pthreads)库。以下是一个简单的示例,展示了如何使用 readdir 和 pthreads 读取目录内容:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <pthread.h>
typedef struct {
char *path;
} thread_data_t;
void *read_directory(void *arg) {
DIR *dir = opendir(arg->path);
if (dir == NULL) {
perror("opendir");
pthread_exit(NULL);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("Thread %ld: %s\n", pthread_self(), entry->d_name);
}
closedir(dir);
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return 1;
}
pthread_t threads[4];
thread_data_t thread_data[4];
for (int i = 0; i < 4; ++i) {
thread_data[i].path = argv[1];
if (pthread_create(&threads[i], NULL, read_directory, (void *)&thread_data[i]) != 0) {
perror("pthread_create");
return 1;
}
}
for (int i = 0; i < 4; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
在这个示例中,我们创建了一个名为 read_directory 的函数,它接受一个指向 thread_data_t 结构的指针作为参数。这个结构包含一个目录路径。read_directory 函数使用 readdir 读取目录内容,并将每个文件名打印到控制台。
在 main 函数中,我们创建了四个线程,每个线程都调用 read_directory 函数。我们将目录路径传递给每个线程,以便它们可以读取相同的目录。
请注意,这个示例程序没有处理潜在的竞争条件,因为多个线程同时访问和打印相同的控制台。在实际应用中,您可能需要使用互斥锁或其他同步原语来确保线程安全。