Each thread is being passed a pointer to the arg_struct
that is declared inside the loop, which is created anew on each iteration. If none of the threads execute until you exit the loop, they are technically referencing a variable that has gone out of scope. Even if it hadn't gone out of scope (say you declared it at the top of main
), they would all see the final value that you placed there. From your trace, it appears that the threads are starting in random clumps relative to the loop.
You will need to allocate a separate arg_struct
for each thread, and make sure that each one remains valid for the lifetime of the thread.
Try this:
#define NUM_THREADS 10
int main() {
int i = 0;
pthread_t threads[NUM_THREADS];
arg_struct args[NUM_THREADS];
for (i = 0; i < NUM_THREADS; i++) {
args[i].id = i;
args[i].val = i + 10;
pthread_create(&threads[i], NULL, &printarg, &args[i]);
}
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}