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?
Asked
Active
Viewed 311 times
-1
-
The accepted solution works fine in C. – Fredrik Dec 03 '18 at 23:31
-
@Fredrik new int(i) causes it to not compile – Is12Prime Dec 03 '18 at 23:33
-
Ofc not that is C++. allocate a new int for each thread and pass it to the function. That was the answer, so just do that in C. – Fredrik Dec 03 '18 at 23:35
-
@Fredrik I tried declaring int j = i, and then passing in j instead of i, but that didn't work either - is this not the right way to do it (I'm new to C)? – Is12Prime Dec 03 '18 at 23:37
-
int *numberToPass = malloc(sizeof int); *numberToPass = i; Then pass numberToPass to the thread. – Fredrik Dec 03 '18 at 23:39
-
"it does not work" is not a problem description – klutt Dec 03 '18 at 23:43
-
@Fredrik Thank you, that worked perfectly – Is12Prime Dec 03 '18 at 23:44
-
@Is12Prime, The answer from Tony Delroy in the link you have given should solve your problem. – Jay Dec 04 '18 at 08:58
1 Answers
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