在C中的pthread_create中传递一个int作为第四个参数

时间:2014-11-10 11:05:55

标签: c multithreading



int threadreader(void* pos)
{
    int a, v;
    char *f;

    v = (long int) *pos;

    f = (char *)malloc(sizeof(SIZEFICHEIRO));
    a = randomnum(4);
    f = pickfile(a, f);
    return reader (v, f);
}


int main(){

    int i, pos, extra, retval,safe;
    pthread_t thread[K];

    for (i = 0; i < K; i++) 
    {
        pos = i * L/K * SIZECADEIA;
        safe = pthread_create( &thread[i], NULL, (void*) threadleitor, (void*) &pos);
        if (safe != 0)
        {
            perror ("Error creating threads");
        }
    }
&#13;
&#13;
&#13;

我试图将pos的值传递给函数threadreader,因为我在函数阅读器中需要它。问题是在pthread_create的第四个参数中,只有当我放置pos(&amp; pos)的地址时它才有效。最后,当我尝试再次访问pos的值时,会打印出以下错误:

&#13;
&#13;
warning: dereferencing ‘void *’ pointer [enabled by default]
     v = (long int) *pos;
                    ^
reader3.c:92:5: error: invalid use of void expression
     v = (long int) *pos;
&#13;
&#13;
&#13;

我知道怎么解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

首先将void指针强制转换为int指针,然后取消引用该值。像这样:

int threadreader(void* pos)
{
    int* p_pos = (int*) pos;
    int v = *p_pos;

    return v;
}

正如评论者指出的那样,你应该确保指针指向一个在线程运行时仍然“活着”的变量。

答案 1 :(得分:0)

修复编译错误不是问题,但程序逻辑不正确。线程运行时,指向局部变量pos的指针可能无效。这是未定义的行为。将pos值传递给线程而不是指针:

int threadreader(void* pos)
{
    int v = (int) pos;
    ...
}

int pos;
...
pos = i * L/K * SIZECADEIA;
safe = pthread_create( &thread[i], NULL, (void*) threadreader, (void*) pos);

通常,如果要将指针传递给线程,请确保该指针存在的变量存在且具有预期值。

BTW,线程函数必须返回void*而不是inthttp://man7.org/linux/man-pages/man3/pthread_create.3.html