I am practicing concurrent programming. My ultimate goal is applying the multiple thread on OpenCV and 3rd party software. I am reading the following URL.
http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)i);
It returns me an error.
$ g++ simpleThread.cpp -lpthread
simpleThread.cpp: In function ‘int main()’:
simpleThread.cpp:25:47: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
PrintHello, (void *)i);
Then I read http://stackoverflow.com/questions/21323628/warning-cast-to-from-pointer-from-to-integer-of-different-size
Add long
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)(long)i);
Program works.
Question :
I don't understand at all. Why I have to put long
in here?
Where, what topic, book, URLs I can start?
Update :
Thank you everyone for your attention.
Casting by long
returns me acceptable result.
rc = pthread_create(&threads[i], NULL,
PrintHello, (void*)(long)i);
Run the program.
$./simpleThreadLong.out
main() : creating thread, 0
main() : creating thread, 1
Hello World! Thread ID, 0
main() : creating thread, Hello World! Thread ID, 2
1
main() : creating thread, 3
Hello World! Thread ID, 2
main() : creating thread, 4
Hello World! Thread ID, 3
Hello World! Thread ID, 4
Whereas ampersand returns unknown ID.
rc = pthread_create(&threads[i], NULL,
PrintHello, &i);
Run the program.
./simpleThreadAmpersand.out
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
Hello World! Thread ID, 140722119501784
Hello World! Thread ID, 140722119501784
Hello World! Thread ID, 140722119501784
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 140722119501784
Hello World! Thread ID, 140722119501784
Update2:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
int main ()
{
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
//rc = pthread_create(&threads[i], NULL,
// PrintHello, (void *)(long)i);
rc = pthread_create(&threads[i], NULL,
PrintHello, &i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}