beard
beard

Reputation: 91

Correct way to pass a struct to pthread within a for loop

1. Question: I need to pass a struct containing two integers to a pthread_create call.

This is within a for loop that calculates the values of the struct. Ideally I would like each thread to call the updatePlates() with a different struct.

2. Problem: I create the structs {1,2},{3,4},{5,6} but by the time the thread begins working they all have the value {5,6}. It was my incorrect understanding that Tuple t; is a new temporary variable each loop iteration. But my debug statement cout<< "t: " << &t << endl; reveals them to have the same memory address every loop.

3. Real Question: What is the correct way to create a 'new' struct and pass it to each thread with unique un-shared values?

pthread_t updateThreads[THREADS];
for(size_t i = 0; i < THREADS; ++i)
{
    Tuple t;
    t.start = 1 + (i * increment);
    t.end = t.start + increment -1;
    // Debug Statements //
    cout << "start: " << t.start <<endl;
    cout << "end:   " << t.end <<endl;
    cout << "t:     " << &t <<endl;
    // End Debug //
    returnCode = pthread_create(&updateThreads[i], NULL, updatePlates, (void *)&t);
}
for(size_t i = 0; i < THREADS; ++i)
{
    pthread_join(updateThreads[i], NULL);
}

Upvotes: 2

Views: 1560

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21619

Allocate them on the heap

Tuple* t = new Tuple;

assign the values

t->start = 1 + (i * increment);
t->end = t->start + increment -1;

pass to pthread_create

returnCode = pthread_create(&updateThreads[i], NULL, updatePlates, (void *)t);

Then in updatePlates free the Tuple.

void* updatePlates(void* data)
{
    Tuple* t = (Tuple*)data;

    // do stuff

    delete t;
    return NULL;
}

Alternatively as you know how many threads you have, you could define an array of Tuples and pass the index into the array to the pthread_create call. But be sure that array stays in scope for the lifetime of the thread function.

Upvotes: 3

Related Questions