Search code examples
c++linuxmultithreadingposix

Unique value within POSIX thread


I am trying to pass into each thread a struct and have each thread print out the value within the struct and show that it is unique per thread.

My problem is that each thread prints out the same value even though i change the value right before passing it in.

const int NUM_THREADS = 2;

struct number
{
    int uniqueNumber;
};

void* showUniqueNumber(void* numberStruct);

int main()
{
    pthread_t threadID[NUM_THREADS];

    number* numberPtr = new number();

    for(int i=0; i < NUM_THREADS; i++)
    {
        numberPtr->uniqueNumber = i;
        pthread_create(&threadID[i], NULL, showUniqueNumber, (void*)numberPtr);
    }

    for(int i=0; i < 5; i++)
    {
        pthread_join(threadID[i], NULL);
    }

    return 0;
}

void* showUniqueNumber(void* numberStruct)
{
    number* threadPtrN = (number*)numberStruct;

    cout << threadPtrN->uniqueNumber << endl;

    return (void*)0;
}

Solution

  • It's because it's the same object. You can do this:

    pthread_t threadID[NUM_THREADS];
    number numbers[NUM_THREADS];
    
    for(int i = 0; i < NUM_THREADS; i++)
    {
        numbers[i].uniqueNumber = i;
        pthread_create(&threadID[i], NULL, showUniqueNumber, numbers + i);
    }