c
, эквивалентный вашему связанному вопросу, немного сложнее.
Чтобы предотвратить состояние гонки (мы участвуем в гонке с основным потоком, который увеличивается i
), мы можем't просто сделайте:
pthread_create(&p[i],NULL,somefunc,(void *) &i);
Итак, нам нужно сделать то, что делает new
, но в c
.Итак, мы используем malloc
(а функция потока должна делать 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;
}