gpt4 book ai didi

c++ - 如何在 C++ 中进行多线程文件处理?

转载 作者:行者123 更新时间:2023-11-30 04:01:53 27 4
gpt4 key购买 nike

我正在处理一个问题,我需要处理 24 个文件(每个文件大小 = 3 GB)并将输出写入多个文件 (24)。每个文件大约需要 1 小时来处理。是否可以通过以下代码使用多线程将数据同时写入多个文件?

 int _tmain(int argc, _TCHAR* argv[])
{
std::string path;
cout << "Enter the folder of the logs: " << endl;
cin >> path;

WIN32_FIND_DATA FileInformation; // File information
memset(&FileInformation, 0, sizeof(WIN32_FIND_DATA));
std::string strExt = "\\*.txt";
std::string strEscape = "\\";
std::string strPattern = path + strExt;
HANDLE hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);

while(hFile != INVALID_HANDLE_VALUE)
{
int offset;
std::ifstream Myfile;
std::string strFileName = FileInformation.cFileName;
std:: string fullPath = path + strEscape + strFileName;
std::string outputFile = path + strEscape + strFileName.substr(0, strFileName.length()-3) + "processed"+".txt";
std::ofstream ofs(outputFile, std::ofstream::out);

Myfile.open (fullPath);
std::string line;

if(Myfile.is_open())
{
while(!Myfile.eof())
{
-------Processing--------
}

Myfile.close();

}
else
cout<<"Cannot open file."<<endl;

if(FindNextFile(hFile, &FileInformation) == FALSE)
break;
}
// Close handle
::FindClose(hFile);
return 0;

}

最佳答案

查看您的代码,我假设您从一个输入生成一个输出文件。在这种情况下,您不需要编写多线程代码来检查一次处理多个文件是否会加快进程。只需修改您的程序以接受文件名作为参数并并行运行其中的多个。但是,除非您正在从 SSD 驱动器读取/写入,否则这种并行处理很可能会减慢处理速度,因为硬盘驱动器必须在多个位置的读取/写入之间切换,而且磁头定位很慢。

不清楚您在处理什么,但如果它占用 100% 的 CPU,那么您很可能会通过多个线程处理一个文件来显着加快处理速度。您将有一个线程读取,然后是线程池处理,然后是一个线程写入。棘手的部分是同步数据并使其不会以错误的顺序出现在输出文件中。

关于c++ - 如何在 C++ 中进行多线程文件处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com