代码
#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