Not sure if there's a portable way to create a timer event, but if main
doesn't have anything else to do, it could simply call sleep
to waste time.
As for signaling the threads, you have two choices: cooperative termination or non-cooperative termination. With cooperative termination, the thread must periodically check a flag to see if it's supposed to terminate. With non-cooperative termination, you call pthread_cancel
to end the thread. (See the man page for pthread_cancel
for information about additional functions that can be used to gracefully end the thread.)
I find cooperative termination easier to implement. Here's an example:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
static int QuitFlag = 0;
static pthread_mutex_t QuitMutex = PTHREAD_MUTEX_INITIALIZER;
void setQuitFlag( void )
{
pthread_mutex_lock( &QuitMutex );
QuitFlag = 1;
pthread_mutex_unlock( &QuitMutex );
}
int shouldQuit( void )
{
int temp;
pthread_mutex_lock( &QuitMutex );
temp = QuitFlag;
pthread_mutex_unlock( &QuitMutex );
return temp;
}
void *somefunc( void *arg )
{
while ( !shouldQuit() )
{
fprintf( stderr, "still running...\n");
sleep( 2 );
}
fprintf( stderr, "quitting now...\n" );
return( NULL );
}
int main( void )
{
pthread_t threadID;
if ( pthread_create( &threadID, NULL, somefunc, NULL) != 0 )
{
perror( "create" );
return 1;
}
sleep( 5 );
setQuitFlag();
pthread_join( threadID, NULL );
fprintf( stderr, "end of main\n" );
}