I\'m learning Pthreads. My code executes the way I want it to, I\'m able to use it. But it gives me a warning on compilation.
I compile using:
gcc
I was also getting the same warning. So to resolve my warning I converted int to long and then this warning just vanished. And about the warning "cast to pointer from integer of different size" you can leave this warning because a pointer can hold the value of any variable because pointer in 64x is of 64 bit and in 32x is of 32 bit.
pthread_create(&(tid[i]), &attr, runner, (void *) i);
You are passing the local variable i
as an argument for runner
, sizeof(void*) == 8
and sizeof(int) == 4
(64 bits).
If you want to pass i
, you should wrap it as a pointer or something:
void *runner(void * param) {
int id = *((int*)param);
delete param;
}
int tid = new int; *tid = i;
pthread_create(&(tid[i]), &attr, runner, tid);
You may just want i
, and in that case, the following should be safe (but far from recommended):
void *runner(void * param) {
int id = (int)param;
}
pthread_create(&(tid[i]), &attr, runner, (void*)(unsigned long long)(i));
A quick hacky fix might just to cast to long
instead of int
. On a lot of systems, sizeof(long) == sizeof(void *)
.
A better idea might be to use intptr_t
.
int threadnumber = (intptr_t) param;
and
pthread_create(&(tid[i]), &attr, runner, (void *)(intptr_t)i);
Try passing
pthread_create(&(tid[i]), &attr, runner, (void*)&i);