linuxtimer.h

#ifndef ___LINUXTIMER_H___
#define ___LINUXTIMER_H___

void *timers();

#endif 

linuxtimer.c

#include "../inc/linuxtimer.h"
#include "../inc/callback.h"

int count = 0;

void *timers() {
    
    while (1) {
        count++;
        //通过回调函数把时间传过去 当异步线程用
        do_something(1, count);
        sleep(1);
    }
}

callback.h

#ifndef __CALLBACK_H__
#define __CALLBACK_H__
#ifdef __cplusplus
extern "C" {
#endif
    //函数定义
    typedef void(*callback_t)(int event_id, int code, int value2, unsigned char *buffer);

    void set_callback(callback_t callback);
    void do_something();

#ifdef __cplusplus
}
#endif
#endif    // __CALLBACK_H__

callback.c

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "../inc/callback.h"

static callback_t g_notify;
int mqttid = 0;

void set_callback(callback_t callback){
    g_notify = callback;
}

void do_something(int ev,int code){
    char *buf = "timer";
    g_notify(ev, code, 0, buf);
}

main.c

#include "../inc/linuxtimer.h"
#include "../inc/callback.h"
#include <pthread.h>

static pthread_t timer_thread;

void do_notify(int event_id, int code, int value2, unsigned char *buffer) {
    if(event_id == 1){
        printf("code=====%d",code);
    }
    
}

int main(int argc, char *argv[])
{
    set_callback(do_notify);

    pthread_create(&timer_thread, NULL, &timers, NULL);
    pthread_detach(timer_thread);


    while( 1 ){
      
        sleep(1);
    }
 

    return 0;
}

Logo

更多推荐