In my c++ program I want to make a function that gets called periodically, like once every second. How can I do that?
I am creating a shell in OSX. It should also work the same in Linux. The purpose of this function is to watch spawned programs, and terminate them when they start using too much memory or cpu time.
Ok--here's a pthread solution. Someone may want to check my pthread API usage for correctness, but I verified this works:
#include <stdio.h>
#include <pthread.h>
#define false (0!=0)
static void * TimerRoutine(void *) ;
int main( int argc, const char ** argv)
{
pthread_t thread ;
pthread_attr_t attr ;
pthread_attr_init( & attr ) ;
pthread_create( & thread, & attr, TimerRoutine, NULL ) ;
int done = false ;
while( !done )
{
char input[80] ;
scanf("%79s", input) ;
// handle input command (or something)
done = ( 0 == strcmp( input, "quit" ) ) ;
}
// wait for timer thread to exit
pthread_cancel( thread ) ;
pthread_join( thread, NULL ) ;
}
static void * TimerRoutine(void * arg)
{
pthread_detach( pthread_self() ) ;
int done = false ;
while( !done )
{
// do background task, i.e.:
printf("tick!\n") ;
sleep(1) ;
pthread_testcancel( ) ;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With