UTI.THREAD
我寫的線程類, 用GP技術(shù)和OOP思想對OS的線程創(chuàng)建進行了封裝, 使用起來靈活方便(后附example),力求簡單實用。
這個線程類需要boost庫的頭文件支持, 但無需對boost庫進行編譯, 要知道編譯boost庫是一個漫長的過程... 而且boost庫里面有很多我們平常用不上的一些“高級”玩意:-).
此外, 我還寫了一系列使用靈活、方便,且在編程中經(jīng)常需要使用的類(如同步鎖, 線程池, 同步隊列, 常用I/O對象, 常用算法等), 我其中的大部分放入了uti namespace之中, 所以稱之為uti庫。我盡量保持這些類的相對獨立,一般只需要注釋掉某行就可以單獨使用。總之, 我寫此類庫所奉行的原則是 --- 穩(wěn)定,靈活,簡單(在example中應(yīng)該可以看得到:-)).其他類庫將出現(xiàn)在后續(xù)文章中, 希望大家喜歡, 也希望能和大家交流:-) stlflingfeitang@gmail.com
/*******************************************************************
created: 2008/06/05
created: 5:6:2008
Vision 0.8
file base: uti::thread
file ext: h
author: lingfei.tang
copyright(c) 2008.9
stlflingfeitang@gmail.com
歡迎使用本輕量級的線程類庫---uti::thread
目前版本只支持Win32操作系統(tǒng),且需要boost庫的支持,
但只需引入頭文件, 可免去編譯boost的漫長等待過程
請注意boost::thread是需要編譯才能使用的, 而且已經(jīng)比較龐大復(fù)雜。
本線程庫支持兩種形式的函數(shù)簽名:
1. 若是自由函數(shù)(全局函數(shù)):
RT func_name(PT param);
RT, PT 均已泛化. 即帶一個參數(shù)的自由函數(shù)都滿足條件
2. 若是成員函數(shù):
RT memb_func_name(void);
父類, 和返回型別已經(jīng)被泛化.
以上兩種形式的函數(shù)其實已經(jīng)可以滿足大多數(shù)需求, 且形式簡潔.
***你可以自由使用本庫, 但請保留本說明和作者名及聯(lián)系方式***
0.8版本已經(jīng)過單元測試.
若有問題或建議請與我聯(lián)系:-)stlflingfeitang@gmail.com
This code may be used in compiled form in any way you desire. This
file may be redistributed unmodified by any means PROVIDING it is
not sold for profit without the authors written consent, and
providing that this notice and the authors name and all copyright
notices remains intact.
An email letting me know how you are using it would be nice as well.
This file is provided "as is" with no expressed or implied
warranty.
The author accepts no liability for any damage/loss of business that
this product may cause.
*******************************************************************/
/*--------------------------使用說明-------------------------------
本線程類的使用時簡單且靈活的:
1. 在線程對象的構(gòu)造函數(shù)中傳入你的線程函數(shù)指針, 以及相關(guān)參數(shù)
eg:
void freefunc(void*p){}//自由函數(shù)
uti::thread
thread_1(&freefunc, NULL);
class aclass{public:
threadfunc(){}};
aclass ainstan;//對象
uit::thread thread_2(&aclass::threadfunc,
&ainstan);
2. 調(diào)用start方法即可以啟動線程
eg:
thread_1->start();
thread_2->start();
3. 調(diào)用join方法可以等待線程的退出,在線程對象析構(gòu)時可以保證該線程的退出
eg:
thread_1->join();
thread_2->join();
另外,在后面還提供了兩個用于繼承復(fù)用的包裝類, 繼承復(fù)用可能時最簡單的,但是耦合也是較高的:-)
eg:
class mythreadclass :public
ThreadObjBase
{
void Run
{
//...重寫該線程函數(shù)
}
}
***需要特別說明的是:請確保你的線程函數(shù)是可以解棧的,否則利用該函數(shù)創(chuàng)建的線程將無法退出:(
------------------------------------------------------------------*/
/*modification record
08-08-29 by tlf :為了支持友元方式的訪問, 將Thread_MemFun中的原對象的動態(tài)創(chuàng)建
移到父類thread 中創(chuàng)建.
*/
#if !defined(_UTI_THREAD__)
#define _UTI_THREAD__
//#include "utidef.h"http://如果你想只使用本線程類, 請注釋該行
#include <Windows.h>
#include <process.h>
#include <boost\function.hpp>
#include <boost\shared_ptr.hpp>
#include <vector>
#if !defined(_UTI_DEF__)
#define BEGIN_UTI
#define END_UTI
#else
#include <iostream>
#endif
BEGIN_UTI
class ThreadFunbase
{public: virtual
void run() =
0;};
template<typename
RT, typename CT>
class Thread_MemFun:
public ThreadFunbase
{
public:
typedef RT(CT::*FT)();
explicit Thread_MemFun( RT(CT::*f)(), CT *pcobj):m_fp(f), m_p(pcobj)
{}
virtual void run()
{
if (m_p)
(m_p->*m_fp)();
else
throw
std::logic_error("the thread function have no owner!");
}
private:
CT *m_p;
FT m_fp;
};
template<typename
RT, typename PT>
class Thread_Fun:
public ThreadFunbase
{
public:
explicit Thread_Fun(RT(*f)(PT), PT param){
m_funptor
= f;
m_param
= param;
}
virtual void run()
{
m_funptor(m_param);
}
private:
boost::function1<RT, PT> m_funptor;
PT m_param;
};
class thread
{
public:
template<typename RT, typename CT>
explicit thread(RT(CT::*f)(), CT *pcobj = NULL, std::string thread_name=
""):
m_thread_name(thread_name),m_id(0),
m_threadhandle(0), m_bisrunning(false), m_bisout(true)
{
CT *po = pcobj;
if (NULL == po)
{
get_static_obj_ptr(&po);
}
m_pfunptor.swap(boost::shared_ptr<ThreadFunbase>(new Thread_MemFun<RT, CT>(f, po)));
}
template<typename RT, typename PT>
explicit thread( RT(*f)(PT), PT param, std::string thread_name= ""):
m_thread_name(thread_name),m_id(0),
m_threadhandle(0), m_bisrunning(false)
{
m_pfunptor.swap(boost::shared_ptr<ThreadFunbase>(new Thread_Fun<RT,PT>(f, param)));
}
virtual ~thread()
{
join();
}
inline unsigned int getid() const
{
return m_id;
}
inline void start()
{
if (!m_bisrunning){
m_threadhandle
= reinterpret_cast<HANDLE>
(_beginthreadex(0,
0, threadfun, this,
0, &m_id));
m_bisout
= false;//we must
used it in two thread for sync
while(!m_bisrunning && !m_bisout){
//blocking to waiting thread running
#ifdef ___UTI_DEBUG
std::cout<<"###the
thread is waiting for start! "<< std::endl;
#endif
Sleep(2);
}
//Sleep(8);
}
}
inline bool IsRunning() const
{
return m_bisrunning;
}
inline void join()
{
if (m_threadhandle)
::WaitForSingleObject(m_threadhandle, INFINITE);
::CloseHandle(m_threadhandle);
m_threadhandle
= 0;
}
private:
std::string m_thread_name;
boost::shared_ptr<ThreadFunbase>
m_pfunptor;
HANDLE m_threadhandle;
unsigned int m_id;
bool m_bisrunning;
bool m_bisout;
virtual void run()
{
try{
m_bisrunning
= true;
m_pfunptor->run();
m_bisout
= true;
m_bisrunning
= false;
}
catch(...)
{
throw
std::logic_error("\r\n exception found in thread func! \r\n");
}
}
//now we are in
another thread :-)
static unsigned __stdcall threadfun(void *threadenti)
{
thread *
th = reinterpret_cast<thread*>(threadenti);
th->run();
return 0;
}
template<typename CT> CT *get_static_obj_ptr(CT **po = NULL)
{
static std::vector<boost::shared_ptr<CT> > v_ct;
boost::shared_ptr<CT>
sp_ct(new CT);
v_ct.push_back(sp_ct);
return sp_ct.get();
}
};
class ThreadObjBase
{
public:
enum ATACH_DETACH{ATTCH
= 0, DETACH};
ThreadObjBase(ATACH_DETACH a_or_d
= ATTCH): m_bNeedStop(false), m_a_or_d(a_or_d)
{}
virtual ~ThreadObjBase()
{
m_pth->join();
}
void Start()
{
if (ATTCH == m_a_or_d)
{
m_pth
= boost::shared_ptr<thread>(new thread(&ThreadObjBase::Thread_Start,this));
m_pth->start();
}
if (DETACH == m_a_or_d)
{
m_pth
= boost::shared_ptr<thread>(new thread(&ThreadObjBase::Thread_Start));
m_pth->start();
}
}
inline void NotifyStop()
{
m_bNeedStop
= true;
}
void Join()
{
m_pth->join();
}
public:
virtual void Run(){}
private:
void Thread_Start()
{
Run();
}
boost::shared_ptr<thread>
m_pth;
bool m_bNeedStop;
ATACH_DETACH
m_a_or_d;
};
template <typename
DT>
class ThreadObjBase_T
{
public:
enum ATACH_DETACH{ATTCH
= 0, DETACH};
ThreadObjBase_T(ATACH_DETACH a_or_d
= ATTCH):m_bNeedStop(FALSE), m_a_or_d(a_or_d)
{}
virtual ~ThreadObjBase_T()
{
m_pth->join();
}
void start()
{
if (ATTCH == m_a_or_d){
m_pth
= boost::shared_ptr<thread>(new thread(&DT::Run, static_cast<DT*>(this)));
m_pth->start();
}
if (DETACH == m_a_or_d){
m_pth
= boost::shared_ptr<thread>(new thread(&DT::Run));
m_pth->start();
}
}
inline void notify_stop()
{
m_bNeedStop
= TRUE;
}
void join()
{
m_pth->join();
}
private:
boost::shared_ptr<thread>
m_pth;
bool m_bNeedStop;
ATACH_DETACH
m_a_or_d;
};
END_UTI
#endif
//===================================================================
//example
#include "thread.h"
#include <iostream>
#include <stdlib.h>
bool g_needstop
= false;
int g_count
= 0;
void globle_func(int np)
{
std::cout << "-------
globle_func start--------" <<std::endl;
while(1)
{
if (g_needstop)
break;
std::cout << ">>in
globle_func countint:" <<g_count++
<<" param:" << np << std::endl;
Sleep(200);
}
std::cout << "-------
globle_func exit--------" <<std::endl;
}
class uti_thread_test_cls
{
public:
void mem_func()
{
std::cout << "-------
uti_thread_test_cls::mem_func start--------" <<std::endl;
while(1)
{
if (g_needstop)
break;
std::cout <<">>in
uti_thread_test_cls::mem_func count:"<< g_count++ << std::endl;
Sleep(200);
}
std::cout << "-------
uti_thread_test_cls::mem_func exit--------" <<std::endl;
}
};
//線程類的簡單使用。
int main(int argc, char* argv[])
{
{
thread thread_1(globle_func, 100);
thread_1.start();
uti_thread_test_cls
cls_mem;
thread thread_2(&uti_thread_test_cls::mem_func, &cls_mem);
thread_2.start();
::system("pause\r\n");
g_needstop
= true;
}
::system("pause\r\n");
return 0;
}
昨天我通過zoundry將此文發(fā)表在本BLOG之中, 后來我通過網(wǎng)頁才看到排版很糟糕(至今我還沒有發(fā)現(xiàn)完美的BLOG桌面軟件:-(, 如果大家有什么好的blog桌面軟件也希望可以介紹一下, 在這里先謝謝了 ^_^),
故今天稍作調(diào)整重新發(fā)表。