今天把平时积累的一些比较常用的库给共享出来,一来“展现”下自己的开源精神,二来也可以发表下自己的看法。(假设你熟悉C++ tr1的组件)
共享顺序
1.线程库(线程篇、线程池篇、线程同步与本地线程存储篇)
2.内存库(待续…)
3.网络库(待续…)
一、线程篇(创建和管理单线程)
在Windows下,如果要在某类中创建线程使用,则有如下几个缺点(不方便)
1. 要提供线程句柄的管理
2.要提供线程入口函数(必须为static且具有__stdcall调用方式)
3.要有机制使线程退出(bool、Event、APC…)
4.需要在CreateThread,_beginthreadex,ATL::CreateThreadT,MFC::AfxBeginThread等等做决策
5.还没想到~~
有上述如此之多的不方便和缺点,促使了我开发此组件。该组件有效地解决了上述问题。使用方式:
1.声明类(需要线程的类)成员变量—>ThreadImplEx m_thread;
2.注册线程函数(不需要为static且__stdcall的调用方式,使用类普通成员函数即可__thiscall)—>m_thread.RegisterFunc(std::tr1::bind(….));
3.开始线程—>m_thread.Start()
4.结束线程—>m_thread.Stop();
OK!上组件代码
#ifndef __THREAD_THREAD_HPP
#define __THREAD_THREAD_HPP
#include "../Thread.hpp"
#ifndef ATLTRY
#define ATLTRY(x) (x)
#endif // ATLTRY
namespace DataStructure
{
//-----------------------------------------------------
// CThread
template< bool t_bManaged >
class CThreadT
{
public:
HANDLE m_hThread; // Handle to thread
DWORD m_dwThreadID; // Thread ID
bool m_bSuspended; // Thread currently suspended?
CThreadT(HANDLE hThread = NULL) : m_hThread(hThread), m_dwThreadID(0), m_bSuspended(false)
{
}
~CThreadT()
{
if( t_bManaged ) Release();
}
// Operations
bool Create(LPTHREAD_START_ROUTINE pThreadProc, LPVOID pParam = NULL, int iPriority = THREAD_PRIORITY_NORMAL)
{
_ASSERTE(m_hThread==NULL);
_ASSERTE(pThreadProc);
#if defined(_MT) || defined(_DLL)
m_hThread = (HANDLE) _beginthreadex(NULL, 0, (UINT (WINAPI*)(void*)) pThreadProc, pParam, CREATE_SUSPENDED, (UINT*) &m_dwThreadID);
#else
m_hThread = ::CreateThread(NULL, 0, pThreadProc, pParam, CREATE_SUSPENDED, &m_dwThreadID);
#endif // _MT
if( m_hThread == NULL )
return FALSE;
if( iPriority != THREAD_PRIORITY_NORMAL )
{
if( !::SetThreadPriority(m_hThread, iPriority) )
{
_ASSERTE(!"Couldn't set thread priority");
}
}
return ::ResumeThread(m_hThread) != (DWORD) -1;
}
bool Release()
{
if( m_hThread == NULL )
return TRUE;
if( ::CloseHandle(m_hThread) == FALSE )
return FALSE;
m_hThread = NULL;
m_dwThreadID = 0;
return TRUE;
}
void Attach(HANDLE hThread)
{
_ASSERTE(m_hThread==NULL);
m_hThread = hThread;
}
HANDLE Detach()
{
HANDLE hThread = m_hThread;
m_hThread = NULL;
return hThread;
}
bool SetPriority(int iPriority) const
{
_ASSERTE(m_hThread);
return ::SetThreadPriority(m_hThread, iPriority);
}
int GetPriority() const
{
_ASSERTE(m_hThread);
return ::GetThreadPriority(m_hThread);
}
bool Suspend()
{
_ASSERTE(m_hThread);