在Linux中,readdir
函數用于讀取目錄中的文件和子目錄。要實現并發控制,可以使用互斥鎖(mutex)或其他同步原語來確保多個線程或進程在訪問目錄時不會發生沖突。
以下是一個使用互斥鎖實現并發控制的簡單示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <pthread.h>
pthread_mutex_t lock;
void *read_directory(void *path) {
DIR *dir;
struct dirent *entry;
pthread_mutex_lock(&lock); // 加鎖
dir = opendir((char *)path);
if (dir == NULL) {
perror("opendir");
pthread_mutex_unlock(&lock); // 解鎖
return NULL;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
pthread_mutex_unlock(&lock); // 解鎖
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t threads[5];
int i;
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return 1;
}
pthread_mutex_init(&lock, NULL);
for (i = 0; i < 5; ++i) {
if (pthread_create(&threads[i], NULL, read_directory, (void *)argv[1]) != 0) {
perror("pthread_create");
exit(1);
}
}
for (i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&lock);
return 0;
}
在這個示例中,我們使用pthread_mutex_t
類型的互斥鎖lock
來保護對目錄的訪問。在read_directory
函數中,我們在打開目錄之前鎖定互斥鎖,并在關閉目錄之后解鎖。這樣可以確保在同一時間只有一個線程可以訪問目錄,從而實現并發控制。
需要注意的是,這個示例中的并發控制是粗粒度的,因為每個線程在讀取整個目錄時都會持有鎖。在實際應用中,可以根據需要使用更細粒度的同步原語,例如讀寫鎖(pthread_rwlock_t
),以允許多個線程同時讀取目錄,但在寫入時仍然需要互斥訪問。