The function printHello bellow receives a void pointer as argument. But this pointer gets casted to a long and the code works. I don't think I understand how this conversion works. Aren't pointer type supposed to hold addresses? How is a long type suddenly compatible for conversion into a pointer type and vice-versa?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define NUM_OF_THREADS 5
void *printHello (void *thread_id)
{
long tid;
tid = (long) thread_id; // Why is this possible?
printf("hello from thread #%ld!", tid);
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUM_OF_THREADS];
int return_code;
long i;
for(i=0; i<NUM_OF_THREADS; i++)
{
printf("In main: creating thread %ld\n", i);
return_code = pthread_create(&threads[i],NULL,printHello,(void*) i);
// Why does it allow to cast 'long i' into '(void*) i'?
if(return_code)
{
printf("Error: return code from pthread_create is %d\n", return_code);
exit(-1);
}
}
pthread_exit(NULL);
}
Sample output:
In main: creating thread 0
In main: creating thread 1
hello from thread #0!
hello from thread #1!
In main: creating thread 2
In main: creating thread 3
hello from thread #2!
In main: creating thread 4
hello from thread #3!
hello from thread #4!