C++ 回调 函数的简单示例

代码

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>

typedef int (*func)(int num);

static int test_func(int test)
{
    printf("%s--------:%d\n", __func__,  test);
    return 0;
}
static int s_running = 1;
static void __sig_handle(int signo)
{
    s_running = 0;
}

class TestCallback {
    public:
        TestCallback(){m_nRunning = 0;m_CallbackFunc= NULL;};
        ~TestCallback(){};
        void set_callback_func(func callback){ m_CallbackFunc = callback; };
        void start_thread(){
            m_nRunning = 1;
            pthread_create(&m_CallbackThread, NULL, thread1, this);
        };
        void stop_thread(){
            m_nRunning = 0;
        };

    private:
        static void *thread1(void* param){
            if(NULL != param){
                TestCallback  *pobjTestCallback = (TestCallback *)param;
                return pobjTestCallback->thread1_proccess();
            }
            
            return NULL;
        };

        void *thread1_proccess(void){
            pthread_detach(pthread_self());
            int test_num = 1;
            while(m_nRunning){
                if(m_CallbackFunc){
                    m_CallbackFunc(test_num);
                }
                test_num += 10;
                usleep(1000 * 1000);
            }
            pthread_exit(0);
        };

    private:
        int  m_nRunning;
        func m_CallbackFunc;
        pthread_t m_CallbackThread;
};

int  main()
{
    signal(SIGQUIT, __sig_handle);
    signal(SIGKILL, __sig_handle);

    TestCallback objCallback;
    objCallback.set_callback_func(test_func);
    objCallback.start_thread();

    while(s_running){
        sleep(2);
    }
    
    objCallback.stop_thread();
    return 0;
}

编译

Linux下
linux 下,g++ CallBack.cpp -lpthread -o CallBack

运行

./CallBack
test_func--------:1
test_func--------:11
test_func--------:21
test_func--------:31
test_func--------:41
test_func--------:51
test_func--------:61
test_func--------:71
test_func--------:81
test_func--------:91
test_func--------:101
test_func--------:111
test_func--------:121
test_func--------:131
test_func--------:141
test_func--------:151
test_func--------:161
test_func--------:171
test_func--------:181
test_func--------:191
test_func--------:201
test_func--------:211
test_func--------:221
test_func--------:231

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值