首页 > 解决方案 > For循环的索引作为Pthread中的参数

问题描述

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

标签: cmultithreadingpthreads

解决方案


相当于您的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;
}

推荐阅读