I am using a for loop to create a number of threads and passing the index i as an argument as follows:
pthread_t p[count];
for (int i = 0; i < count; i++){
pthread_create(&p[i], NULL, &somefunc, (void*)&i);
}
Then I attempt to retrieve the value of i:
void *somefunc (void* ptr){
int id = *(int*)ptr;
}
However, I noticed that sometimes, id in the threads will have overlapping values which I suspect is due to the index of the for loop updating before the thread is able to retrieve the value (since I passed in the pointer, as opposed to the value itself). Does anyone have any suggestions to overcome this issue without slowing down the for loop?
Thanks
p
(I'd go so far as to say they typically shouldn't know of or depend on such details of their creator). – Rhianna