在C的pthread_create中将int作为第四个参数传递 [英] Passing an int as the 4th argument in pthread_create in C

查看:76
本文介绍了在C的pthread_create中将int作为第四个参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正试图将pos的值传递给函数threadreader,因为在函数读取器中我将需要它.问题是,在pthread_create的第4个参数中,仅当我放置pos(& pos)的地址时,它才起作用.最后,当我再次尝试访问pos的值时,它会打印出以下错误:

I'm trying to pass the value of pos to the function threadreader because i'll need it then in function reader. The problem is that in the 4th argument of pthread_create it only works if I put the adress of pos (&pos). And in the end, when I try to access to the value of pos again it prints out the following errors:

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;

关于如何解决这个问题的任何想法吗?

Any idea of how I can solve this?

推荐答案

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

First cast the void pointer to an int pointer, and then dereference the value. Like this:

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

    return v;
}

正如注释者所指出的那样,您应该确保指针指向在线程运行时仍然有效"的变量.

As commenters pointed out, you should make sure that the pointer points to a variable that is still "alive" when the thread is run.

这篇关于在C的pthread_create中将int作为第四个参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆