Domanda

It seems that for some reason my pthreads are getting the same parameter even though I'm inputting different strings each time.

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;
}

The first cout is printing what I expect ("file1.txt", "file2.txt", "file3.txt" and so on).

But the second cout gives a lot of repeating ones often starting around 6 or 7 and with a lot of them repeating with 20.

È stato utile?

Soluzione

The char* returned by c_str() will be deleted at the end of the loop body. That means, the behaviour of the program is undefined, and only accidentally, you see the same value in each thread.

It's a lot easier to use threads with C++11. The code might look as follows:

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)
{
    // ...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top