温馨提示×

CentOS readdir如何实现多线程

小樊
38
2025-12-05 19:02:02
栏目: 智能运维

在 CentOS 系统中,实现多线程读取目录(readdir)可以使用 POSIX 线程库(pthread)或者 C++11 的线程库。下面是一个使用 pthread 实现的多线程 readdir 示例:

首先,确保已经安装了 pthread 库。如果没有安装,可以使用以下命令安装:

sudo yum install glibc-devel

然后,创建一个名为 multi_threaded_readdir.c 的文件,并添加以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_THREADS 4

typedef struct {
    char *path;
} thread_data_t;

void *readdir_thread(void *arg) {
    thread_data_t *data = (thread_data_t *)arg;
    DIR *dir = opendir(data->path);

    if (dir == NULL) {
        perror("opendir");
        pthread_exit(NULL);
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    pthread_exit(NULL);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\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];
        if (pthread_create(&threads[i], NULL, readdir_thread, &thread_data[i]) != 0) {
            perror("pthread_create");
            return 1;
        }
    }

    for (int i = 0; i < NUM_THREADS; ++i) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}

编译代码:

gcc -o multi_threaded_readdir multi_threaded_readdir.c -lpthread

运行程序:

./multi_threaded_readdir /path/to/directory

这个示例中,我们创建了 4 个线程,每个线程都会读取指定的目录。请注意,这个示例仅用于演示目的,实际应用中可能需要根据需求进行调整。

0