Reputation: 671
I have a process that creates a number of threads based on an argument passed to the process.
producer_threads[num_threads];
for (id = 0; id < num_threads; id++)
{
printf("%d\n", id);
pthread_create(&producer_threads[id], NULL, &produce, (void *) &id);
}
Each thread goes into a produce function and stores the id as a local variable
void* produce (void* args)
{
int my_id = * (int*) args;
printf("Thread %d started to produce\n", my_id);
}
However the output I receive is as shown
0
1
Thread <n> started to produce
Thread <n> started to produce
and n are randomly either 0, 1, or 2. I am not sure what is causing the problem unless it is because the global variable is being updated before it is assigned locally. Or because the "local variable" is shared between threads.
Upvotes: 2
Views: 1315
Reputation: 7203
The integer needs to be an alloc'd variable instead of a stack variable. Since you're passing a pointer to a memory location on the stack, your results will depend on timing (i.e. are a race condition). You need to pass different variables to each pthread_create call.
Upvotes: 2
Reputation: 500177
The problem is that you're passing pointers to the same variable to each thread. This creates a race condition, whereby the value of the variable as seen by each thread depends on the exact timing.
If you were to pass the thread argument by value rather than by pointer, this would fix the problem.
Upvotes: 3