I have the following functions :
void *foo(void *i) { int a = (int) i; } int main() { pthread_t thread; int i; pthread_create(&thread, 0, foo, (void *) i); }
At compilation, there are some errors about casting ((void *) i
and int a = (int) i
). How can I pass an integer as the last argument of pthread_create
properly?
Building on szx's answer (so give him the credit), here's how it would work in your for
loop:
void *foo(void *i) { int a = *((int *) i); free(i); } int main() { pthread_t thread; for ( int i = 0; i < 10; ++1 ) { int *arg = malloc(sizeof(*arg)); if ( arg == NULL ) { fprintf(stderr, "Couldn't allocate memory for thread arg.\n"); exit(EXIT_FAILURE); } *arg = i; pthread_create(&thread, 0, foo, arg); } /* Wait for threads, etc */ return 0; }
On each iteration of the loop, you're allocating new memory, each with a different address, so the thing that gets passed to pthread_create()
on each iteration is different, so none of your threads ends up trying to access the same memory and you don't get any thread safety issues in the way that you would if you just passed the address of i
. In this case, you could also set up an array and pass the addresses of the elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With