unable to use a function to crate a joinable thread

In my program, threads may be created when some events trigger. So I can't create threads on initialization.

Theremore,I write a createThread() function to create thread. However, it is blocking at first call and don't run anymore? why?

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void *BusyWork(void *t)
{
   int i = 0;
   long tid;
   double result=0.0;
   tid = (long)t;
   printf("Thread %ld starting...\n",tid);
   while ( 1 ) {
      result = result + sin(i) * tan(i);
      i++;
   }
   printf("Thread %ld done. Result = %e\n",tid, result);
   pthread_exit((void*) t);
}


void createThread () {
  int rc;
  void *status;
  pthread_attr_t attr;
  pthread_t thread;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  rc = pthread_create(&thread, &attr, BusyWork, (void *)0); 
  if (rc) {
    printf("ERROR; return code from pthread_create() is %d\n", rc);
    exit(-1);
   }
    pthread_attr_destroy(&attr);
    rc = pthread_join(thread, &status);
    if (rc) {
       printf("ERROR; return code from pthread_join() is %d\n", rc);
       exit(-1);
    }
    printf("Main: completed join with thread %d having a status of %ld\n",0,(long)status);
}

int main (int argc, char *argv[])
{
  createThread();  // <- Blocking here
  createThread();  
  printf("Main: program completed. Exiting.\n");
  pthread_exit(NULL);
}

Thanks for your help!

In your example, you wait for the termination of the BusyWork() thread (using pthread_join) in createThread(). But this thread never terminates because of the while(1) {...}

Hence you get never past the first createThread().

Cheers, Lo�c

Hi, when I write the pthread_create() and pthread_join in this way, then the program is OK.

pthread_create( ... ) <- Thread A
pthread_create( ... ) <- Thread B

pthread_join( ... ) <- Thread A
pthread_join( ... ) <- Thread B

However, I require to design the architecture like

pthread_create( ... ) <- Thread A
pthread_join( ... ) <- Thread A

In my requirement, once some events or signals come, then a thread is created for handle it; if no events then no thread is created.

the thread calling pthread_join() blocks until the targeted thread either returns from the start routine or calls pthread_exit().

That's it. It is difficult for us to help you further (the reason why your example didn't worked is clear - but doesn't seem to reflect your real problem?).

Cheers, Lo�c

There's no reason to start a separate thread if all you're going to do is call pthread_join() and wait for it to finish.