[英]Threads seem to be getting the same thread argument when they should be different (PThreads)
似乎由于某种原因我的pthreads获得了相同的参数,即使我每次都输入不同的字符串。
int* max = new int[numberOfFiles];
pthread_t* threads = new pthread_t[numberOfFiles];
for(int i = 0; i < numberOfFiles; i++)
{
stringstream filestream;
filestream << "file" << i + 1 << ".txt";
string message = filestream.str();
pthread_create(&threads[i], NULL, findLargestInFile, (void*)message.c_str());
cout << message << endl;
}
...
void* findLargestInFile(void* rawFileName)
{
char* fileName = (char*)rawFileName;
cout << fileName << endl;
}
第一个cout打印我期望的内容(“file1.txt”,“file2.txt”,“file3.txt”等)。
但是第二个cout给出了很多重复的,通常在6或7左右开始,并且很多重复的是20。
c_str()
返回的char*
将在循环体的末尾删除。 这意味着,程序的行为是未定义的,只是偶然地,您在每个线程中看到相同的值。
使用C ++ 11的线程要容易得多。 代码可能如下所示:
std::vector<std::thread> threads;
for (int i = 0; i < numberOfFiles; ++i) {
std::stringstream filestream;
filestream << "file" << i + 1 << ".txt";
std::string message = filestream.str();
threads.emplace_back(&findLargestInFile, message);
}
void findLargestInFile(std::string rawFileName)
{
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.