加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

定期调用的c函数

发布时间:2020-12-16 10:29:12 所属栏目:百科 来源:网络整理
导读:在我的程序中,我想创建一个定期调用的函数,比如每秒一次.我怎样才能做到这一点? 我在OSX中创建一个shell.它在Linux中也应该是一样的.此函数的目的是观察生成的程序,并在它们开始使用太多内存或CPU时间时终止它们. 解决方法 好的 – 这是一个pthread解决方案
在我的程序中,我想创建一个定期调用的函数,比如每秒一次.我怎样才能做到这一点?

我在OSX中创建一个shell.它在Linux中也应该是一样的.此函数的目的是观察生成的程序,并在它们开始使用太多内存或CPU时间时终止它们.

解决方法

好的 – 这是一个pthread解决方案.有人可能想检查我的pthread API使用情况是否正确,但我验证了这个有效:

#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( ) ;
    }   
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读