poco 线程类 学习

运行业务逻辑的类都继承自Runnable类
Runnable类中带有纯虚函数run()

class Runnable
/// The Runnable interface with the run() method
/// must be implemented by classes that provide
/// an entry point for a thread.
{
public:	
Runnable();
virtual ~Runnable();

virtual void run() = 0;
/// Do whatever the thread needs to do. Must
/// be overridden by subclasses.
};

Runnable::Runnable()
{
}


Runnable::~Runnable()
{
}

  

而继承自Runnable类的各种业务逻辑类均实现自己的run 由于Thread类
进行调用。Thread类控制start 以及stop
类似

XClass x; // 某个类
Thread thread;
thread.start(x);

Thread类流程如下:

void Thread::start(Runnable& target)
{
    startImpl(target);
}

void ThreadImpl::startImpl(Runnable& target)
{
    // 这里将业务逻辑类的指针赋予给_pRunnableTarget 
    _pRunnableTarget = ⌖

    createImpl(runnableEntry, this);
}

//createImpl函数 运行线程函数 ent也就是(runnableEntry
void ThreadImpl::createImpl(Entry ent, void* pData)
{
#if defined(_DLL)
    _thread = CreateThread(NULL, _stackSize, ent, pData, 0, 

&_threadId);
#else
    unsigned threadId;
    _thread = (HANDLE) _beginthreadex(NULL, _stackSize, 

ent, this, 0, &threadId);
    _threadId = static_cast<DWORD>(threadId);
#endif
}


unsigned __stdcall ThreadImpl::runnableEntry(void* pThread)

{
    try
    {
        //    void ThreadImpl::startImpl(Runnable& target)
     //  函数中已经记录业务逻辑类指针
// _pRunnableTarget就是之前赋值的业务逻辑类 reinterpret_cast<ThreadImpl*>(pThread)->_pRunnableTarget->run(); } return 0; }

自己模拟了一个简单类型,没有使用ThreadImpl.vs2008代码

#include <windows.h>
#include <iostream>
#include <process.h>

using namespace std;

class CRunnable
{
public:
    CRunnable() {}
    ~CRunnable() {}
    virtual void run() = 0;
};

class CTest: public CRunnable
{
    virtual void run() {cout << __FUNCTION__ << endl;}
};



class CThread
{
    HANDLE    _thread;
    CRunnable* _pRunnableTarget;
public:
    void threadCleanup();
    void join();
    static unsigned __stdcall runnableEntry(void* pThread);
    void start(CRunnable& runnable);
};

unsigned __stdcall CThread::runnableEntry(void* pThread)
{
    reinterpret_cast<CThread*>(pThread)->_pRunnableTarget-

>run();

    return 0;
}

void CThread::start(CRunnable& runnable)
{
    unsigned int threadId;

    _pRunnableTarget = &runnable;

    _thread = (HANDLE) _beginthreadex(NULL, 0, 

runnableEntry, this, 0, &threadId);
}


void CThread::threadCleanup()
{
    if (!_thread) return;
    if (CloseHandle(_thread)) 
        _thread = 0;
}

void CThread::join()
{
    if (!_thread) return;

    switch (WaitForSingleObject(_thread, INFINITE))
    {
    case WAIT_OBJECT_0:
        threadCleanup();
        return;
    }
}



int _tmain(int argc, _TCHAR* argv[])
{
    CTest threadTest;
    CThread thread;

    thread.start(threadTest);
    thread.join();

    return 0;
}

 

posted on 2014-11-25 14:38  itdef  阅读(354)  评论(0)    收藏  举报

导航