[wxWidgets]_[初级]_[wxThread使用简单介绍]


场景:

1.wx里自带了wxThread线程,使用起来比较方便,但是wx的线程使用时必须创建一个wxThread子类,这样会造成文件数量的增多,编译时间增长。

2.可以使用函数指针来解决这个问题。当然如果有类似Java那种的匿名子类最好了。


文件1: task_thread.h


#ifndef TASK_THREAD_H
#define	TASK_THREAD_H

#include "wx/thread.h"

typedef void (*THREAD_TASK)(void* data);

/**
 *  通用任务线程,不依赖于wxWindow
 *
 */
class TaskThread : public wxThread
{
public:
    TaskThread();
    TaskThread(void* userdata, THREAD_TASK process,
            THREAD_TASK preprocess = NULL, THREAD_TASK postprocess = NULL);
    virtual ~TaskThread();
    virtual void* Entry();
    void Execute();
    void RegistRunTask(THREAD_TASK fr);
    void RegistSetupTask(THREAD_TASK fs);
    void RegistTeardownTask(THREAD_TASK ft);
private:
    void* data_;
    THREAD_TASK process_;
    THREAD_TASK preprocess_;
    THREAD_TASK postprocess_;
};

#endif	/* TASKTHREAD_H */


文件2:task_thread.cpp

/*
 * File:   task_thread.cpp
 * Author: Administrator
 *
 * Created on 2010年5月10日, 上午10:57
 */

#include "common/task_thread.h"

void TaskThread::Execute()
{
    Create();
    Run();
}

TaskThread::TaskThread(void* userdata, THREAD_TASK process,
        THREAD_TASK preprocess, THREAD_TASK postprocess) : wxThread()
{
    data_ = userdata;
    process_ = process;
    preprocess_ = preprocess;
    postprocess_ = postprocess;
    //preprocess
    if (preprocess_)
    {
        preprocess_(data_);
    }
}

TaskThread::TaskThread() : process_(NULL), preprocess_(NULL), postprocess_(NULL)
{
}

TaskThread::~TaskThread()
{
	//postprocess
	if (postprocess_)
	{
		postprocess_(data_);
	}
}

void* TaskThread::Entry()
{
    //process
    if (process_)
    {
        process_(data_);
    }

    return 0;
}

void TaskThread::RegistRunTask(THREAD_TASK fr)
{
    process_ = fr;
}

void TaskThread::RegistSetupTask(THREAD_TASK fs)
{
    preprocess_ = fs;
}

void TaskThread::RegistTeardownTask(THREAD_TASK ft)
{
    postprocess_ = ft;
}

调用方式:

TaskThread* tt = new TaskThread(cd, &DomainConvert::DoAddFolderTask);
tt->Execute();



你可能感兴趣的:(函数指针,wxwidgets,wxThread)