拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何有效地为此撰写函式?

如何有效地为此撰写函式?

白鹭 - 2022-03-07 1948 0 0

我有一个长字符串,我将其分成较短的字符串并将它们并行化。如何撰写一个函式来传递执行绪数并将字符串分成那么多较短的段?

这就是我一直在做的

//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 整除会发生什么。会有更好的方法处理执行绪也完成了检查。

希望它应该对您有所帮助。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *