1

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;
}
user7195486
  • 33
  • 1
  • 1
  • 8

1 Answers1

0

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);
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • thanks for this, could i ask a question here without creating a new post, as its related: What if i had 2 structs, one of them had to be shared between all threads and the other unique like the one above? how would i pass both to thread as it only accepts a void* If you know that answer then thats great! – user7195486 Dec 10 '16 at 13:52
  • @user7195486 You should do a other question, I can't do a proper answer in comment. You must have a struct that contain this two data. Like that for example `struct all { struct foo *shared, struct bar not_shared };` – Stargateur Dec 10 '16 at 13:57
  • 1
    amazing, will ask another question, thankyou for the concise answer – user7195486 Dec 10 '16 at 13:58