尝试让我的线程工作有点麻烦。我是新手,所以我不太确定我遇到了什么问题。
std::thread* activeThread = new std::thread[threadCount];
std::condition_variable* tempvar = new std::condition_variable();
std::mutex* tempmut = new std::mutex();
for (int i = threadCount - 1; i >= 0; i--)
{
perThreadData[i].id = i;
perThreadData[i].sharedStringLength = sharedStringLength;
perThreadData[i].numberOfStringsToGenerate = numberOfStringsToGenerate;
perThreadData[i].waitTime = waitTime;
perThreadData[i].sharedString = sharedString;
perThreadData[i].runType = runType;
perThreadData[i].conVar = tempvar;
perThreadData[i].mutex = tempmut;
activeThread[i] = std::thread( ThreadEntryPoint, &perThreadData[i] );
}
for( int i = 0; i < threadCount; i++ ) {
activeThread[i].join();
}
这是入口点功能:
void ThreadEntryPoint(ThreadStruct *threadData)
{
for(int i = 0; i < threadData->numberOfStringsToGenerate; i++)
{
if( threadData->runType == 3 )
{
threadData->mutex->lock();
}
if(threadData->waitTime != 0)
{
// Blocks the current thread for a given amount of time.
std::this_thread::sleep_for(std::chrono::milliseconds(threadData->waitTime));
}
if( threadData->runType == 1 ){
threadData->mutex->lock();
}
for(int j = 0; j < threadData->sharedStringLength; j++)
{
if( threadData->runType != 3 ) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
threadData->sharedString[j] = 'A' + threadData->id;
}
printf("Thread %d: %s\n", threadData->id, threadData->sharedString);
if( threadData->runType == 1 ) {
threadData->mutex->unlock();
}
}
}
RunType应该根据输入执行此操作:
0 - 按原设计运行
1 - 运行所以线程的每个字符串始终是相同的字母
2 - 运行以便线程在允许任何其他线程进行迭代之前完成所有迭代
3 - 运行以便线程始终以线程0的顺序运行到线程n