#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 4
/* function to be executed by the new thread*/
void *PrintHello(void * threadid)
{
printf("\n %3d:Hello World!\n",threadid);
pthread_exit(NULL);
}
int main(int argc, char * argv[])
{
int *taskids[NUM_THREADS];
int rc,t;
pthread_t threads[NUM_THREADS];
for (t = 0; t < NUM_THREADS;t++)
{
taskids[t] = (int *)malloc(sizeof(int));
*taskids[t]=t;
printf("Creating thread %d\n",t);
printf(" The number in array is %d\n",*taskids[t]);
rc = pthread_create(&threads[t],NULL,PrintHello,(void *)&taskids[t]);
if (rc){
printf("ERROR;return code from pthread_create() is %d\n",rc);
exit(-1);
}
}
pthread_exit(NULL);
}
The above code is taken form the lecture notes at
www.llnl.gov/computing/tutorials/pthreads under the topic passing arguments. When i run it on Sun SOlaris 9, the answe is wrong. Here is the answer: I cant detect the logic error.. PLease help.
Creating thread 0
The number in array is 0
Creating thread 1
The number in array is 1
-4195784:Hello World!
Creating thread 2
The number in array is 2
Creating thread 3
The number in array is 3
-4195780:Hello World!
-4195776:Hello World!
-4195772:Hello World!