I have a long string which I separate to shorter strings and parallelize them. How to write a function which passes the thread count and separates the string to that many shorter segments?
This is how I've been doing
//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();
}
What is a better way to write this?
CodePudding user response:
I think you should use a loop because you have a number of lines of code that are almost identical.
Using your code as a base:
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();
}
This is just the next step (I haven't compiled it), there are still issues you will need to handle, such as what happens if content.Length() is not divisible by 4. There is going to be a better way of handling the has the thread finished check as well.
Hopefully it should help you a bit.
