我自己的线程类, 比mfc的那个简单,灵活

类别:编程语言 点击:0 评论:0 推荐:

这是范例, 头文件在后边
#pragma warning(disable: 4530)
#pragma warning(disable: 4786)

#include <cassert>
#include <iostream>
#include <exception>
#include <algorithm>
#include <math.h>
#include <iomanip>
using namespace std;

#include <winsock2.h>
#include <windows.h>

#include "cxThread.h"

cxLocker coutLock; //输出的锁

int comp(const void *a, const void *b)
{
 return *(char*)a - *(char*)b;
}

void dos_sort_func(void *p)
{
 cxLock lock(coutLock); //生存期自动锁, 不需要UnLock();

 char *t = new char[strlen((char *)p) + 1];
 strcpy(t, (char *)p);
 qsort(t, strlen(t), 1, comp);
 cout << (char *)t << endl;
 delete t;
}

DWORD WINAPI win_sort_func(LPVOID p)
{
 cxLock lock(coutLock);
 char *t = new char[strlen((char *)p) + 1];
 strcpy(t, (char *)p);
 sort(t, t + strlen((char *)t));
 cout << (char *)t << endl;
 delete t;
 return 0;
}

class MyThread : public cxThread
{
 char buf[20];

protected:

 virtual DWORD ThreadProc()  
 { 
  cxLock lock(coutLock);
  sort(buf, buf + strlen((char *)buf));
  cout << buf << endl;
  return 0;            
 }

public:

 MyThread()
 {
  strcpy(buf, "xdeefde");
 }
 
};

 

int main(int argc, char *argv[])
{
 try
 {
  char buf[] = "adceafeadb";
  cxThread mt;
  MyThread myt;
  mt.Run(dos_sort_func, buf);    //调用dos风格的函数
  mt.Wait();

  mt.Run(win_sort_func, buf);    //调用windows风格的函数
  mt.Wait();

  myt.Run();       //调用自定义的虚函数
  myt.Wait();
 }
 catch(exception *e)
 {
  cout << e->what() << endl;
 }
 return 0;
}

//-----------------------------------------cxThread.h-------------------------------------------------

/*
thread (WIN32) 

Compile by: BC++ 5; C++ BUILDER 4, 5, 6, X; VC++ 5, 6; VC.NET;  GCC;

Update : 2004.11

copyright(c) 2004.5 - 2004.11  llbird [email protected]
*/

#ifndef _CX_THREAD_H_
#define _CX_THREAD_H_

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

//------------------------------class cxLocker-----------------------------------

class cxLocker
{
 CRITICAL_SECTION _csLock;
public:
 cxLocker()       {  ::InitializeCriticalSection(&_csLock);  }
 ~cxLocker()      {  ::DeleteCriticalSection(&_csLock);   }
 operator CRITICAL_SECTION*() {  return  &_csLock;       }
 void Lock()      {  ::EnterCriticalSection(&_csLock);   }
 void UnLock()     {  ::LeaveCriticalSection(&_csLock);   }
};

//------------------------------class cxLock-----------------------------------

class cxLock
{
 CRITICAL_SECTION* _pLock;
public:
 explicit cxLock(CRITICAL_SECTION * p) : _pLock(p) { ::EnterCriticalSection(_pLock);  }
 ~cxLock()           { ::LeaveCriticalSection(_pLock);  }
};

//------------------------------class cxEvent-----------------------------------

class cxEvent
{
 HANDLE _hEvent;
 cxEvent(const cxEvent&);
 cxEvent& operator = (const cxEvent& x);
public:

//------------------------------Construction-----------------------------------
 
 cxEvent(HANDLE Event) : _hEvent(Event)
 {
 }

 cxEvent(char *pName) : _hEvent(Create(NULL, FALSE, FALSE, pName)) 
 {
 } 

 cxEvent(
  LPSECURITY_ATTRIBUTES  lpEventAttributes = NULL,
  BOOL bManualReset = FALSE,
  BOOL bInitialState = FALSE,
  char *pName = NULL
  ) : _hEvent(Create(lpEventAttributes, bManualReset, bInitialState, pName))
 {
 }

 ~cxEvent()    
 {
  if(_hEvent) 
   ::CloseHandle(_hEvent);            
 }
 
//----------------------------------Attributes----------------------------------

 operator HANDLE() {  return _hEvent;     }
 bool IsValid()  {  return _hEvent != NULL;   }

//----------------------------------Operations----------------------------------
 
 HANDLE Create(
  LPSECURITY_ATTRIBUTES  lpEventAttributes = NULL,
  BOOL bManualReset = FALSE,
  BOOL bInitialState = FALSE,
  char *pName = NULL
  )
 {
  HANDLE hTemp = ::CreateEvent(lpEventAttributes, bManualReset, bInitialState, pName);
  return hTemp;
 }

 bool Wait(DWORD dwWaitTime = INFINITE) 
 {
  return ::WaitForSingleObject(_hEvent, dwWaitTime) == WAIT_OBJECT_0;
 }

    BOOL Reset()  {  return ::ResetEvent(_hEvent); }
    BOOL Set()   {  return ::SetEvent(_hEvent);  }
    BOOL Pulse()   {  return ::PulseEvent(_hEvent); }
};

//------------------------------class cxThread-----------------------------------

class cxThread
{
private:

 static DWORD WINAPI DefaultThreadProc(LPVOID lpPara)
 {
  return ( (cxThread *)lpPara ) -> ThreadProc();
 }
 cxThread(const cxThread&);
 cxThread& operator = (const cxThread& x);
 cxLocker _ThreadLocker;

protected:

 virtual DWORD ThreadProc()  {  return 0;            }
 HANDLE _hThreadHandle;
 DWORD _dwThreadID;

public:

//------------------------------Construction-----------------------------------

 cxThread()      {  _hThreadHandle = NULL, _dwThreadID = 0;     }
 virtual ~cxThread()    {  Terminate();           }

//----------------------------------Attributes----------------------------------

 operator HANDLE()     {   return _hThreadHandle;         }
 const HANDLE GetThreadHandle() {  return _hThreadHandle;         }
 const DWORD GetThreadID()   {  return _dwThreadID;          }
 bool IsRunning()    {  return _hThreadHandle != NULL;        }
 BOOL GetPriority()    {  return GetThreadPriority(_hThreadHandle) ;    }
 BOOL SetPriority(int iPriority) {  return SetThreadPriority(_hThreadHandle, iPriority); }

//----------------------------------Operations----------------------------------

 inline void Lock()    {  _ThreadLocker.Lock();         }
 inline void UnLock()   {  _ThreadLocker.UnLock();         }

 inline bool virtual Begin(DWORD dwCreationFlags = 0)  // Begin equal run
 {  
  return Run(dwCreationFlags); 
 }

 inline bool virtual Begin(LPTHREAD_START_ROUTINE threadProc, LPVOID lpPara = NULL, DWORD dwCreationFlags = 0)
 {
  return Run(threadProc, lpPara, dwCreationFlags);
 }
  
 bool virtual Run(DWORD dwCreationFlags = 0)
 {
  if(IsRunning())
   Stop();

  _hThreadHandle = CreateThread(NULL, 0, cxThread::DefaultThreadProc, this, dwCreationFlags, &_dwThreadID);

  return  IsRunning();
 };

 bool virtual Run(LPTHREAD_START_ROUTINE threadProc, LPVOID lpPara = NULL, DWORD dwCreationFlags = 0)
 {
  assert(threadProc != NULL);

  if(IsRunning())
   Stop();

  _hThreadHandle = CreateThread(NULL, 0, threadProc, lpPara, dwCreationFlags, &_dwThreadID);

  return  IsRunning();
 };

#ifdef  _MT

 inline bool virtual Begin(void( __cdecl *threadProc )( void * ), LPVOID lpPara = NULL)
 {
  return Run(threadProc, lpPara);
 }

 inline bool virtual Begin(unsigned ( __stdcall *threadProc )( void * ), LPVOID lpPara = NULL, DWORD dwCreationFlags = 0)
 {
  return Run(threadProc, lpPara, dwCreationFlags);
 }

 bool virtual Run(void( __cdecl *threadProc )( void * ), LPVOID lpPara = NULL)
 {
  assert(threadProc != NULL);

  if(IsRunning())
   Stop();

  _hThreadHandle = (HANDLE)_beginthread(threadProc, 0, lpPara);

  if(_hThreadHandle == (HANDLE) -1L)
   _hThreadHandle = NULL;

  return  IsRunning();
 };

 bool virtual Run(unsigned ( __stdcall *threadProc )( void * ), LPVOID lpPara = NULL, DWORD dwCreationFlags = 0)
 {
  assert(threadProc != NULL);

  if(IsRunning())
   Stop();

  _hThreadHandle = (HANDLE)_beginthreadex(NULL, 0, threadProc, lpPara, dwCreationFlags, (unsigned int *)&_dwThreadID);

  return  IsRunning();
 };
 
#endif  // _MT

 inline void virtual End(DWORD dwEndCode = 0)
 {
  Terminate(dwEndCode);
 }

 void virtual Terminate(DWORD dwEndCode = 0)
 {
  if(IsRunning())
  {
   TerminateThread(_hThreadHandle, dwEndCode);
   CloseHandle(_hThreadHandle);
   _hThreadHandle = NULL;
  }
 }

 void virtual Stop(DWORD dwEndCode = 0)
 {
  Terminate(dwEndCode);
 }

 bool Wait(DWORD dwWaitTime = INFINITE) //Wait the Thread Auto Terminate in (dwWaitTime)
 {
  return WaitForSingleObject(_hThreadHandle, dwWaitTime) == WAIT_OBJECT_0;
 }

 virtual bool Suspend()
 {
  return SuspendThread(_hThreadHandle) != (DWORD)(-1L);
 }

 virtual bool Resume()
 {
  return ResumeThread(_hThreadHandle) != (DWORD)(-1L);
 }
 
} ;

#endif //_CX_THREAD_H_



本文地址:http://com.8s8s.com/it/it24629.htm