Nurullah Nurullah - 8 months ago 55
C Question

Error : cannot initialize a variable of type 'int' with an lvalue of type 'void'

I am trying pthread example. Here is my code:

void*AsalK1(void *gelen);
int main(){

int *i;
i= new int;

int sonSayi;
pthread_t th1, th2, th3, th4;
printf("| Threadler ile Asal Sayi Bulma |\n");
printf("Son sayi degeri: 1000000 \n");

int r1=pthread_create( &th1, NULL, AsalK1, (void *)i);
int r2=pthread_create( &th2, NULL, AsalK1, (void *)i);
int r3=pthread_create( &th3, NULL, AsalK1, (void *)i);
int r4=pthread_create( &th4, NULL, AsalK1, (void *)i);

pthread_join( th1, NULL);
pthread_join( th2, NULL);
pthread_join( th3, NULL);
pthread_join( th4, NULL);
return 0;
void *AsalK1(void *gelen){
int bas= *gelen;
printf("bas :&d\n",bas);

and i use this code to compile :

gcc -lpthread ThreadDeneme.cpp


g++ -lpthread ThreadDeneme.cpp

And the Error Says:

cannot initialize a variable of type 'int' with an lvalue of type
'void' int bas= *gelen;

I use this:

int bas= (int *) gelen;

but error still in progress.

I read:

What is the difference between these uses of pointers?

usr usr
Answer Source

1) You are not allowed to dereference a void *. So,

int bas= *gelen;

isn't going to work. The correct way to read the int is:

int bas= *(int*)gelen;

2) But this isn't going to work either. Because the same address i is passed to all the 4 threads and that results in data race. So, you need to pass different address to each thread in order to avoid data race (or use some form of synchronization).

3) Your thread function AsalK1() should return a pointer (See pthread_create()'s requirement for the thread function). You can simply return a NULL pointer since you are not returning anything from the thread to main thread.

4) Another potential problem is how you compile:

gcc -lpthread ThreadDeneme.cpp

The library should be at the end of the commandline option. So, you compile as:

gcc ThreadDeneme.cpp -lpthread

Another related suggestion: you can use array instead of using 4 different thread id variables (th1..4). It would allow to use a loop for thread creation and joining and you can easily change the number of threads as well.