您的位置:首页 > 其它

Poco_Thread的用法

2018-03-29 15:40 183 查看
    Poco_Thread 中所有的业务逻辑全部在Runnable里面,Thread类只负责开始(Start)和停止(Join)两个动作。
下面贴出一个示例一看便明白;
// Poco_thread_2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include <iostream>
using namespace std;

class HelloRunnable : public Poco::Runnable
{
virtual void run()
{
for(int i=0;i<30;i++)
{
Sleep(1000);
cout << i++ << endl;
}
}
};

int main(int argc,int **argv[])
{
HelloRunnable runnable;
Poco::Thread thread;
thread.start(runnable);
thread.join();

getchar();

return 0;
}众所周知在VC中创建线程的入口函数需要一个全局函数或静态函数,而在实际工程中线程是不停的变化来满足工程需求的,那么如何来封装Thread来满足其实际所需呢?
分析如下: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
if (!_thread)
throw SystemException("cannot create thread");
if (_prio != PRIO_NORMAL_IMPL && !SetThreadPriority(_thread, _prio))
throw SystemException("cannot set thread priority");
}

#if defined(_DLL)
DWORD WINAPI ThreadImpl::callableEntry(LPVOID pThread)
#else
unsigned __stdcall ThreadImpl::callableEntry(void* pThread)
#endif
{
_currentThreadHolder.set(reinterpret_cast<ThreadImpl*>(pThread));
#if defined(_DEBUG) && defined(POCO_WIN32_DEBUGGER_THREAD_NAMES)
setThreadName(-1, reinterpret_cast<Thread*>(pThread)->getName().c_str());
#endif
try
{
ThreadImpl* pTI = reinterpret_cast<ThreadImpl*>(pThread);
pTI->_callbackTarget.callback(pTI->_callbackTarget.pData);
}
catch (Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
return 0;
}
由源码看出在创建线程时候
void ThreadImpl::createImpl(Entry ent, void* pData)自己便携带了一个this指针用于指向线程对象本身;线程对象本身封装了一个CallbackDate,
Callback指向了真实的业务路口,不同的线程对象在初始化时,会被赋值不同的业务入口函数;
静态函数callbackEntry中,调用this指针运行真正的业务函数;
ThreadImpl* pTI = reinterpret_cast<ThreadImpl*>(pThread);
pTI->_callbackTarget.callback(pTI->_callbackTarget.pData);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: