将int作为C中pthread_create中的第4个参数传递

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的第四个参数中,只有当我放置pos(&pos)的地址时它才有效。 最后,当我尝试再次访问pos的值时,它会输出以下错误:

 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; 

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

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

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

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

修复编译错误不是问题,但程序逻辑不正确。 当线程正在运行时,指向局部变量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); 

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

顺便说一句,线程函数必须返回void*而不是int : http : //man7.org/linux/man-pages/man3/pthread_create.3.html