-1

I have the same issue as with this question here. However, I am using C, not C++ and can't follow the accepted solution. I have tried using the second solution but that does not work either. Is there any way that I can pass the value of the loop variable and not the variable itself in C?

Is12Prime
  • 111
  • 6

1 Answers1

0

The c equivalent to your linked question is slightly more involved.

To prevent a race condition (we're racing against the main thread which is incrementing i), we can't simply do:

pthread_create(&p[i],NULL,somefunc,(void *) &i);

So, we need to do what new does, but in c. So, we use malloc (and the thread function should do free):

#include <pthread.h>
#include <stdlib.h>

void *
somefunc(void *ptr)
{
    int id = *(int*) ptr;

    // main thread _could_ free this after pthread_join, but it would need to
    // remember it -- easier to do it here
    free(ptr);

    // do stuff ...

    return (void *) 0;
}

int
main(void)
{
    int count = 10;
    pthread_t p[count];

    for (int i = 0; i < count; i++) {
        int *ptr = malloc(sizeof(int));
        *ptr = i;
        pthread_create(&p[i],NULL,somefunc,ptr);
    }

    for (int i = 0; i < count; i++)
        pthread_join(p[i],NULL);

    return 0;
}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • pthread_create(&p[i],NULL,somefunc,(void *) i); - This actually works if typecasted appropriately in the thread_func. This will not have any race condition with main thread as you are only passing a value and not a pointer. Can you explain, why do you think it will not work? – Jay Dec 04 '18 at 08:59
  • @Jay It was a typo on my part. I didn't put the `&` in as in the linked page. This was just to recode the solution in `c` – Craig Estey Dec 04 '18 at 09:12