在Linux中,使用readdir
函數可以讀取目錄中的文件和子目錄。要實現多線程讀取,可以將目錄分割成多個部分,然后為每個部分創建一個線程來執行readdir
操作。下面是一個簡單的示例,使用C++11線程庫實現多線程讀取目錄:
#include <iostream>
#include <dirent.h>
#include <vector>
#include <thread>
#include <mutex>
std::mutex mtx;
void read_directory(const std::string &path, int start, int end) {
DIR *dir = opendir(path.c_str());
if (!dir) {
std::cerr << "Error opening directory: " << path << std::endl;
return;
}
struct dirent *entry;
int count = 0;
while ((entry = readdir(dir)) != nullptr) {
if (count >= start && count < end) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << entry->d_name << std::endl;
}
count++;
}
closedir(dir);
}
int main() {
std::string path = "/path/to/your/directory";
DIR *dir = opendir(path.c_str());
if (!dir) {
std::cerr << "Error opening directory: " << path << std::endl;
return 1;
}
struct dirent *entry;
int file_count = 0;
while ((entry = readdir(dir)) != nullptr) {
file_count++;
}
closedir(dir);
int num_threads = 4;
std::vector<std::thread> threads;
int files_per_thread = file_count / num_threads;
for (int i = 0; i < num_threads; ++i) {
int start = i * files_per_thread;
int end = (i == num_threads - 1) ? file_count : (start + files_per_thread);
threads.push_back(std::thread(read_directory, path, start, end));
}
for (auto &t : threads) {
t.join();
}
return 0;
}
這個示例中,我們首先計算目錄中的文件數量,然后將文件平均分配給每個線程。每個線程讀取分配給它的文件,并將文件名輸出到控制臺。注意,這個示例沒有處理目錄中的.
和..
條目,你可能需要根據實際需求進行調整。
編譯并運行此程序,它將使用多個線程讀取指定目錄中的文件。請確保在編譯時鏈接C++11線程庫,例如使用g++ -std=c++11 -pthread your_program.cpp -o your_program
。