c-For循环的索引作为Pthread中的参数



我有与这里的问题相同的问题。然而,我使用的是C,而不是C++,并且无法遵循公认的解决方案。我尝试过使用第二种解决方案,但也不起作用。有没有什么方法可以让我传递循环变量的值,而不是C中的变量本身?

相当于链接问题的c稍微涉及更多。

为了防止竞争条件(我们正在与递增i的主线程竞争(,我们不能简单地执行:

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;
}

最新更新