我有一個長字串,我將其分成較短的字串并將它們并行化。如何撰寫一個函式來傳遞執行緒數并將字串分成那么多較短的段?
這就是我一直在做的
//Thread count is 4
seg = content.length() / 4;
string dataSeg1, dataSeg2, dataSeg3, dataSeg4;
dataSeg1 = content.substr(0, seg);
dataSeg2 = content.substr(seg, seg * 2);
dataSeg3 = content.substr(seg * 2, seg * 3);
dataSeg4 = content.substr(seg * 3, seg * 4);
thread t1(printLen, dataSeg1);
thread t2(printLen, dataSeg2);
thread t3(printLen, dataSeg3);
thread t4(printLen, dataSeg4);
if (t1.joinable())
{
t1.join();
}
if (t2.joinable())
{
t2.join();
}
if (t3.joinable())
{
t3.join;
}
if (t4.joinable())
{
t4.join();
}
有什么更好的方法來寫這個?
uj5u.com熱心網友回復:
我認為您應該使用回圈,因為您有許多幾乎相同的代碼行。
使用您的代碼作為基礎:
static const unsigned int numberOfThreads = 4;
const size_t segmentLength = content.length() / numberOfThreads;
std::vector<thread> threads;
for (int threadCount = 0; threadCount < numberOfThreads; threadCount)
{
threads.push_back(thread(printLen, content.substr((seg * threadCount), ((seg 1) * threadCount));
}
for (auto thread : threads)
{
if (thread.joinable())
thread.join();
}
這只是下一步(我還沒有編譯),還有一些問題需要處理,例如如果 content.Length() 不能被 4 整除會發生什么。會有更好的方法處理執行緒也完成了檢查。
希望它應該對您有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407133.html
標籤:
