Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A c++ function that periodically gets called

Tags:

c++

function

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.

like image 732
node ninja Avatar asked Oct 21 '25 07:10

node ninja


1 Answers

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( ) ;
    }   
}
like image 148
nielsbot Avatar answered Oct 23 '25 20:10

nielsbot