Doubango代码学习(五):runnable

来源:互联网 发布:苏州plc编程培训 编辑:程序博客网 时间:2024/05/20 20:18

代码在tsk_runnable.h(c)中。

有一个tsk_runnable_t的结构体,如下:

typedef struct tsk_runnable_s
{
    TSK_DECLARE_OBJECT;
    
    const tsk_object_def_t *objdef;
    
    tsk_thread_handle_t* h_thread[1];
    tsk_runnable_func_run run;
    tsk_thread_id_t id_thread; // no way to get this value from "h_thread" on WINXP
    tsk_semaphore_handle_t *semaphore;
    
    tsk_bool_t running;
    tsk_bool_t started;
    tsk_bool_t initialized;
    /** whether the enqueued data are important or not.
    * if yes, the thread will not be joined until all data in the queue have been consumed.
    * default value: tsk_false
    */
    tsk_bool_t important;

    int32_t priority;
    
    tsk_list_t *objects;
}
tsk_runnable_t;

可以看出,它是一个类,但这个类没有实例化过,全部是作为基类用的。可以理解为虚类(当然,这里面也没有这个概念)。派生类有tsip_stack_t,tnet_transport_t, tdav_runnable_video_t等。继承直接在第一句包含TSK_DECLARE_RUNNABLE就行了。

tsk_runnable_t顾名思义,就是可自行的。当你需要一个线程执行你的任务时,这就是一个比较好的选择。

总结一下用法:

1,编写一个结构体继承tsk_runnable_t,方法就是把TSK_DECLARE_RUNNABLE放到结构体的第一句就行了。

2,由于TSK_DECLARE_RUNNABLE继承于OBJECT,因此你也需要按照之前的OBJECT章节描述的,来定义你的类对象(包括构造函数,销毁函数和比较函数)。

3,用tsk_object_new来生成你的对象。

4,tsk_runnable_start来执行你的对象。注意要先设置好run函数。一般都是用来事件处理,run函数读取事件,然后处理。循环处理代码夹在TSK_RUNNABLE_RUN_BEGIN和TSK_RUNNABLE_RUN_END之间,用TSK_RUNNABLE_POP_FIRST来取出消息。消息生产者用TSK_RUNNABLE_ENQUEUE_OBJECT来发送消息。

5,tsk_runnable_stop来停止你的对象。

6, 还有一些辅助的宏,注意他们的用法,如TSK_RUNNABLE_RUN_BEGIN, TSK_RUNNABLE_RUN_END,TSK_RUNNABLE_ENQUEUE_OBJECT等。

0 0