我正在尝试创建一个线程,从我记得这应该是正确的方法:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
int SharedVariable =0;
void SimpleThread(int which)
{
int num,val;
for(num=0; num<20; num++){
if(random() > RAND_MAX / 2)
usleep(10);
val = SharedVariable;
printf("*** thread %d sees value %d\n", which, val);
SharedVariable = val+1;
}
val=SharedVariable;
printf("Thread %d sees final value %d\n", which, val);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t< NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, SimpleThread, (void* )t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
而我得到的错误就是这个:
test.c:在函数'main'中:test.c:28:警告:从不兼容的指针类型/usr/include/pthread.h:227传递'pthread_create'的参数3:注意:预期'void () (void )'但参数的类型为'void()(int)'
我无法更改SimpleThread函数,因此更改参数类型不是一个选项,即使我已经尝试过它也不起作用 .
我究竟做错了什么?
2 回答
SimpleThread
应声明为将参数传递给线程时,最好为它们定义
struct
,将指针传递给struct
作为void*
,然后在函数内部转换回正确的类型 .这里's a compiling and 642963 version of your program, although I have to admit to not knowing exactly what it'正在做 . 对于 Spectator 中的评论家,我最后为最后的
pthread_join
循环道歉 .