[英]How to Multithread reading, processing and writing data in Qt C++?
我對 Qt 和 C++ 比較陌生,完全是自學的。 我正在嘗試對我目前在單個線程上工作的任務進行多線程處理。
我的任務如下:
正在讀取的示例文件:
Col1, Col2, Col3, Col4, . . . ColN
1, A, B, C, . . . X
2, D, E, F, . . . Y
3, G, H, J, . . . Z
., ., ., ., . . . .
., ., ., ., . . . .
N, ., ., ., . . . .
這是一些顯示原理的sudo代碼:
for (int i = 0; i < N; i = i + 1)
{
// there are multiple nested for loops, but only one shown here
// calculate multiple variables. Here are two examples:
calculatedVariable = Col2[i] + Col3[i] / Col4 [i];
calculatedVariable2 = (Col2[i] * 0.98) / (Col2[i] + Col3[i] + Col4[i]) + (Col2[i] + Col3[i])
// then write the calculated variables to an output text file
output << calculatedVariable << "," << calculatedVariable2 << std::endl;
}
這很有效,因為代碼在每次循環迭代結束時寫入輸出文本文件,因此它不會阻塞 RAM(即,不是進行所有計算,而是存儲在向量中,然后一次性將數據全部寫入)。
我的問題是這些文件可能有數十萬行,處理可能需要幾個小時。 如果我可以多線程,這樣可以同時對多個數據索引進行處理,同時保持輸出文件中數據的順序,它將大大減少計算時間。 在這個階段我不需要多線程讀取數據。
我目前在解決這個問題的概念方面苦苦掙扎,在網上找不到任何類似的例子。 我已經將 QtConcurrent 視為一個選項,但不太確定如何應用它。
如果有人能指出我正確的方向,那將不勝感激。 謝謝你。
編輯1:感謝您的回復。 所以瓶頸是通過一些長時間的迭代計算對數據的實際處理,而不是IO操作。 假設我讀了 2 個文件,每個文件有 1000 行。 如果我想為文件 2 中的每一行對文件 1 中的每一行進行一些計算,那就是 1,000,000 個案例。 如果有某種方法可以將這些計算的任務分成 10 個線程,那將大大縮短處理時間。
基本上,你想要這個。 隨意將下面的 std:: 機制替換為它們的 Qt 等價物(QString 與 std::string 等......)
struct Job
{
std::string inputFileName;
std::string outputFileName;
};
std::queue<Job> jobs;
// not shown - populate jobs with the input/output names of files you want to manage
std::mutex m;
unsigned int nthreads = std::thread::hardware_concurrency();
vector<std::thread> threads;
for (unsigned int i = 0; i < nthreads; i++) {
std::thread t = [&m, &jobs] {
while (true) {
Job job;
{
std::lock_guard<std::mutex> lck(m); // acquire the lock that protects jobs
if jobs.empty() {
return; // the queue is empty, this thread can exit
}
job = jobs.front();
jobs.pop();
}
// YOUR CODE GOES HERE
// Open the file job.inputFileName and read in the contents
// Open the output file job.outputFileName
// then do your processing and write to the output file handle
// close your files
// all done for this file - loop back to the top of this lambda function and get the next file
}
};
threads.push_back(std::move(t));
}
// wait for all threads to finish
for (auto& t : threads) {
t.join();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.