当前位置:   article > 正文

Linux + C + pthread_create + sleep() +回调计时器写法_pthread_create 睡眠

pthread_create 睡眠

linuxtimer.h

  1. #ifndef ___LINUXTIMER_H___
  2. #define ___LINUXTIMER_H___
  3. void *timers();
  4. #endif

linuxtimer.c

  1. #include "../inc/linuxtimer.h"
  2. #include "../inc/callback.h"
  3. int count = 0;
  4. void *timers() {
  5. while (1) {
  6. count++;
  7.         //通过回调函数把时间传过去 当异步线程用
  8.         do_something(1, count);
  9. sleep(1);
  10. }
  11. }

callback.h

  1. #ifndef __CALLBACK_H__
  2. #define __CALLBACK_H__
  3. #ifdef __cplusplus
  4. extern "C" {
  5. #endif
  6.     //函数定义
  7. typedef void(*callback_t)(int event_id, int code, int value2, unsigned char *buffer);
  8. void set_callback(callback_t callback);
  9. void do_something();
  10. #ifdef __cplusplus
  11. }
  12. #endif
  13. #endif // __CALLBACK_H__

callback.c

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pthread.h>
  6. #include "../inc/callback.h"
  7. static callback_t g_notify;
  8. int mqttid = 0;
  9. void set_callback(callback_t callback){
  10. g_notify = callback;
  11. }
  12. void do_something(int ev,int code){
  13. char *buf = "timer";
  14. g_notify(ev, code, 0, buf);
  15. }

main.c

  1. #include "../inc/linuxtimer.h"
  2. #include "../inc/callback.h"
  3. #include <pthread.h>
  4. static pthread_t timer_thread;
  5. void do_notify(int event_id, int code, int value2, unsigned char *buffer) {
  6.     if(event_id == 1){
  7.         printf("code=====%d",code);
  8.     }
  9.    
  10. }
  11. int main(int argc, char *argv[])
  12. {
  13.     set_callback(do_notify);
  14. pthread_create(&timer_thread, NULL, &timers, NULL);
  15. pthread_detach(timer_thread);
  16. while( 1 ){
  17. sleep(1);
  18. }
  19. return 0;
  20. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/182006
推荐阅读
相关标签
  

闽ICP备14008679号