Search code examples
cmultithreadingpthreadsposix

How to wake up a sleeping thread from the main Thread?


I have a capture program which in addition do capturing data and writing it into a file also prints some statistics.The function that prints the statistics

static void report(void)
{
         /*Print statistics*/
}

is called roughly every second using an ALARM that expires every second.So The program is like

void capture_program()
{
       pthread_t report_thread

            while()
            {
                     if(pthread_create(&report_thread,NULL,report,NULL)){
                            fprintf(stderr,"Error creating reporting thread! \n");
                     }

                     /*
                        Capturing code
                        --------------
                        --------------
                      */
                      if(doreport)
                             /*wakeup the sleeping thread.*/

            }
}

void *report(void *param)
{
       //access some register from hardware
       //sleep for a second 

}

The expiry of the timer sets the doreport flag.If this flag is set report() is called which clears the flag.

How do I wake up the sleeping thread (that runs the report()) when the timer goes off in the main thread?


Solution

  • How do I wake up the sleeping thread (that runs the report()) when the timer goes off in the main thread?

    I think a condition variable is the mechanism you are looking for. Have the report-thread block on the condition variable, and the main thread signal the condition variable whenever you want the report-thread to wake up (see the link for more detailed instructions).