views:

244

answers:

2

Hi, i was trying to write a simple multithreaded program. It is dumping the core. I have my function that is called when a thread is created below:

void *BusyWork(void *t)
{
   int i;
   int *tid;
   int result=0;
   tid = t;

   printf("Thread %d starting...\n",*tid);
   for (i=0; i<10; i++)
   {
       result = result + (i* i);
   }
   printf("thread %d is sleeping for %d sec's\n",tid,tid);
   sleep(tid);
   printf("Thread %d done. Result = %e\n",tid, result);
   pthread_exit((void*) t);
}

My call to pthread_create function is below inside the main function:

int t;

for(t=0; t<NUM_THREADS; t++) 
{
      printf("Main: creating thread %d\n", t);
      rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
}

Please help me in finding where is the problem? Thanks in advance.

A: 

This line is wrong:

printf("Thread %d starting...\n",*tid);

You can achieve what you want with:

printf("Thread %d starting...\n",(int) t);

or printf("Thread %d starting...\n", tid);

Gonzalo
thanks a lot gonzalo.
Vijay Sarathi
A: 

Beginning with this line:

printf("thread %d is sleeping...

All of the references to tid should be *tid.

Paul McGuire
hi paul...could you please also explain why?
Vijay Sarathi
Because tid is not an integer, but a pointer to an integer. C being so tolerant as it is of integer-like types, you may actually get an output value, but it wont be a nice friendly integer like 4 or 7, but some 32-bit memory address that *points* to a 4 or a 7. Since your thread process does not modify the value pointed to by this pointer, I would suggest changing your declaration of tid from `int *tid` to `int tid`, and assign to it using `tid = *t;` Now it is just a plain ol' friendly integer. None of this explains why you are getting a core dump though.
Paul McGuire
Paul McGuire