(二)thread的动态管理
为更加充分灵活的使用计算机的资源,我提供了多线程的机制.然而使用多线程并不是一件十分简单的事情,前面我提到的线程与c++共存就是其中的一个.下面解决下一个问题.线程是一个有生命周期的机制,我们可能需要一个线程与进程"同寿"(主线程),也可能用完了就让线程消失(一个解码GIF图片的线程).达到这个目的并不是很难,只要实现实现一个thread mananger来负责该功能就可以了.为了不至于影响进程的主处理流程,我将该功能是在一个线程里面这样就不会影响其他线程的正常工作了.
class cESThreadManager:public cESThread
{
public:
virtual ~cESThreadManager(){
thread_manager_lock.start_syc();//多个线程同时访问的互斥锁定
if (p_thread_manager) DEL(p_thread_manager);
for (DWD32 i = 0; thread_ctl_tbl[i] && i < MAX_THREAD_NUMBER; i++){
unregister_thread(i);
}
thread_manager_lock.stop_syc();
thread_manager_lock.~cESSycObject();
}
static cESThreadManager* instance(void)//singleton保证进程内部只有一个thread manager
{
if (!p_thread_manager)
p_thread_manager = NEW cESThreadManager;
return p_thread_manager;
}
struct cESThreadInfo{
//cESThreadInfo():thread_id(-1),enabled(true){}
cESThreadInfo(DWD32 id = -1, bool en = false, HANDLE h = NULL, cESThread* p = NULL):
thread_id(id),
enabled(en),
handle(h),
p_temp_thread(p){}
HANDLE handle;
volatile DWD32 thread_id;
//pthread_id used for operate the thread
//other info needed
volatile bool enabled;
cESThread* p_temp_thread;
};
/*The thread manager is not registered!*/
VOID start(VOID){ start_thread("Thread Manager"); }
VOID stop(VOID){ stop_thread(); }
static DWD32 register_thread(cESThreadInfo* p);
static void unregister_thread(DWD32 thread_id);
static bool is_thread_enabled(DWD32 thread_id);
static void kill_thread(DWD32 thread_id);
virtual VOID thread_function();
private:
cESThreadManager();
static cESThreadManager* p_thread_manager;
static cESThreadInfo* thread_ctl_tbl[MAX_THREAD_NUMBER];//存储各个thread注册进来的信息
//each new thread should register the info
//in cESThreadManager,this table record the
//enable status of thread_id's
protected:
static cESSycObject thread_manager_lock;
};
阅读(1303) | 评论(0) | 转发(0) |