C语言通过线程实现回调机制

来源:互联网 发布:复杂网络节点介数 编辑:程序博客网 时间:2024/06/01 10:12
//author:foolishflyfox//说明:该程序用于简单演示通过多线程对回调函数的实现异步操作//由于只是演示作用,故代码相对简陋//编程过程中的几点注意//1、通过fork创建的多进程程序,并不共享全局变量//2、if(fork()==0){子进程执行代码}//3、如果子程序退出后,没有被父程序的wait函数或waitpid函数所回收,而且父程序没有退出,该子程序将成为僵尸进程//  如果父进程退出,所有的僵尸子进程也被结束//4、查看所有僵尸子进程:ps -A -ostat,ppid,pid,cmd | grep -e '^[zZ]'//5、gcc编译线程程序,需要添加 -lpthread//6、定义函数指针类型:typedef void (*v_fv)(void);//定义了一个参数和返回值都是void的函数指针#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <iostream>#include <list>#include <sys/types.h>#include <sys/wait.h>#include <pthread.h>using namespace std;//自定义队列,指定最大的队列空间#define QUEUE_SIZE 10typedef void (*v_fv)(void);typedef void* (*vp_fvp)(void*);//异步执行绑定的任务数,通过检查该值确认还有几个回调函数没有执行int tasksCount = 0;//将执行函数与回调函数进行绑定,形成一个结构体struct S_fcb{    void (*f)(void);    void (*cb)(void);};//执行函数完成后,通过查找该list确定该执行函数对应的回调函数list<S_fcb> f_cb_list;//将传入的f函数以线程的方式进行执行void newThreadExecute(void (*f)(void)){    pthread_t id = 0;    pthread_create(&id,NULL,(vp_fvp)f,NULL);}//对函数f和函数cb进行绑定,并自动启动线程执行f函数void Async(void (*f)(void),void (*cb)(void)){    S_fcb tp_fcb;    tp_fcb.f = f;    tp_fcb.cb = cb;    f_cb_list.push_back(tp_fcb);    newThreadExecute(f);    ++tasksCount;}//自定义队列类,完全可以用STL中的queue替代,接口相同class Queue{public:    Queue():head(0),end(0){}    bool empty(){return head==end;}    bool full(){return (end+1)%QUEUE_SIZE==head;}    void push(void(*f)(void)){        if(full()==false){            pointers[end] = f;            end = (end+1)%QUEUE_SIZE;        }    }    v_fv front(){        return pointers[head];    }    void pop(){        head = (head+1)%QUEUE_SIZE;    }private:    int head;    int end;    v_fv pointers[];};//完成的函数队列Queue fin_queue;void f1(){    cout << "f1 begin to execute!" << endl;    usleep(2000000);    cout << "f1 end execute" << endl;    //执行函数完成后,将自身指针添加到完成队列中    fin_queue.push(f1);}void cb1(){    cout << "cb1 execute!" << endl;}void f2(){    cout << "f2 begin to execute!" << endl;    usleep(3000000);    cout << "f2 end execute" << endl;    fin_queue.push(f2);}void cb2(){    cout << "cb2 execute!" << endl;}//从完成的函数队列中取出完成的执行函数,通过查询取得回调函数并开启线程执行回调函数void CheckTask(){    if(fin_queue.empty())return;    void (*tf)(void);    tf = fin_queue.front();    fin_queue.pop();    list<S_fcb>::iterator begin = f_cb_list.begin();    while(begin!=f_cb_list.end()){        if(begin->f==tf){            newThreadExecute(begin->cb);            break;        }        ++begin;    }    --tasksCount;}int main(){    printf("Begin main function.\n");    //绑定f1和cb1,f2和cb2    Async(f1,cb1);    Async(f2,cb2);    while(tasksCount){        CheckTask();        usleep(5);    }    usleep(1000000);    printf("End main function.\n");    return 0;}
0 0
原创粉丝点击