按"利用C++语言设计可扩展线程池"文章实现代码,但是有问题,希望大家来讨论,指出问题,谢谢

http://blog.csdn.net/tdjdyq/archive/2009/03/06/3964681.aspx

 

利用C++语言设计可扩展线程池

 

/

 

core_threadpool.h

//

 

#ifndef _CORE_THREADPOOL_H_
#define _CORE_THREADPOOL_H_


#include "icl_classes.h"
#include "icl_thread.h"

#include "core_base.h"

#include<deque>


using namespace icl;

#define TIMESJW 60000

class CThreadPool : public CThread
{
friend class CWorkThread;
public:
    CThreadPool( int _size, int nMaxSize);
 ~CThreadPool(void);
 void AddTask(CBase *pBase);
 unsigned int GetThreadCount(void);
 int GetTaskCount();
 void OnTaskIdle(CWorkThread *pThread);
    bool PoolFree();
    void Stop();
private:
    void Destroy(void);
    void DestroyAllThread(void);
    void JoinWithAllThreads(void);
 void Execute(void);
 void GetTask(list<CBase*> &pBaseList,int nSize = 1);
    void SetTask(list<CBase*> pTaskList);
 bool TaskIsEmpty(void);
    CWorkThread* GetIdleThread();
 bool CheckNewTask();
    void CreateNewThread();// 创建新线程
    bool WaitForTaskOrThreadTimeout();
    long IncrIdleTime();
    void DecrIdleThread();
    bool SetThreadTask(list<CBase*> pTaskList);
 void AddTaskToThread(list<CBase*> pTaskList,CWorkThread *pThread);
    int SjwSuspendThread(CWorkThread * pThread);
    int SjwResumeThread(CWorkThread * pThread);
 void UpdateThread();
private:
 const int m_nSize;
    const int m_nMaxSize;
    unsigned int m_nThread;
 unsigned int m_nCount;

    unsigned long m_nLastTime;
    long m_nTime;
 bool m_bStoped;
    bool m_bWorkThreaFree;
 list<CBase*> m_TaskList;
    CCriticalSection m_TaskLock;
    CList m_ThreadList;
    CCriticalSection m_ThreadLock;
    CList m_RunThreadList;
    CCriticalSection m_RunThreadLock;
private:
 CThreadPool(const CThreadPool&);
 CThreadPool& operator=(const CThreadPool&);
};

class CWorkThread : public CThread
{
public:
    CWorkThread(const CThreadPool*);
    ~CWorkThread();
    virtual void Execute(void);
    bool CheckTaskQueue();
    bool WaitForTask();
 CBase* GetTask();
    void SetTaskList(list<CBase*> pTaskList);
    void SetThreadExit(bool bExit){ m_bThreadExit = bExit; }
    bool GetThreadExit(){ return m_bThreadExit; }
    bool GetThreadExitFlag(){ return m_bThreadExitFlag;}
    void SetThreadState(int bFree){ m_nThreadState = bFree; }
    int GetThreadState(){ return m_nThreadState; }
private:
    CThreadPool *m_pool;
 CBase *m_pBaseTask;
    CCriticalSection m_Lock;
 deque<CBase*> m_Queue;
    bool m_bThreadExit;
    bool m_bThreadExitFlag;
    int m_nThreadState; //0,运行;1,没有任务的空闲;2,挂起
};

#endif

 

core_threadpool.cpp

//

 

#include "core_threadpool.h"
#include "icl_socket.h"
#include "icl_sysutils.h"


CThreadPool::CThreadPool( int _size, int nMaxSize):m_nSize(_size),m_nMaxSize(nMaxSize),m_bWorkThreaFree(false),m_nTime(0)
{
    m_nTime = TIMESJW;
    m_nCount = 0;
 m_bStoped = true;
 if(m_nSize < 1)
 {
  const_cast< int &>(m_nSize) = 1;
 }
 for( int i=0; i< m_nSize; i++)
 {
        CWorkThread *hThread = new CWorkThread(this);
  m_ThreadList.Add(hThread);
  hThread->Run();
 }
 m_nCount = m_nSize;
    m_nLastTime = 0;
 m_bStoped = false;
}

CThreadPool::~CThreadPool(void)
{
 Stop();
}

void CThreadPool::Stop()
{
 if(! m_bStoped)
 {
  Destroy();
        DestroyAllThread();
        m_bStoped = true;
 }
}

void CThreadPool::Destroy(void)
{
    CAutoSynchronizer Syncher(m_TaskLock);
 list<CBase*>::iterator it ;
 for(it = m_TaskList.begin(); it != m_TaskList.end(); ++it)
 {
        delete (*it);
 }
    m_TaskList.clear();
}

void CThreadPool::DestroyAllThread(void)
{
    const int MAX_THREAD_WAIT_FOR_SECS = 10; // 线程池清空时最多等待时间(秒)
    const double SLEEP_INTERVAL = 0.5;      // 每次等待的时间间隔(秒)
    double nWaitSecs = 0;

    // 通知线程退出
    {
        CAutoSynchronizer Syncher(m_ThreadLock);
        for (int i = 0; i < m_ThreadList.Count(); i++)
        {
            CWorkThread *pThread;
            pThread = (CWorkThread*)m_ThreadList[i];
            pThread->Terminate();
        }
    }

    // 等待线程退出
    while (nWaitSecs < MAX_THREAD_WAIT_FOR_SECS)
    {
        if (m_ThreadList.Count() == 0) break;
        NanoSleep(SLEEP_INTERVAL, true);
        nWaitSecs += SLEEP_INTERVAL;
    }

    printf("若等待超时,则强行杀死各线程/n");

    // 若等待超时,则强行杀死各线程
    if (m_ThreadList.Count() > 0)
    {
        CAutoSynchronizer Syncher(m_ThreadLock);
        for (int i = 0; i < m_ThreadList.Count(); i++)
        {
            CWorkThread *pThread;
            pThread = (CWorkThread*)m_ThreadList[i];
            pThread->Kill();
        }
        m_ThreadList.Clear();
    }
}

bool CThreadPool::TaskIsEmpty()
{
 CAutoSynchronizer Syncher(m_TaskLock);
    bool bFlag =  m_TaskList.empty();
 return bFlag;

}

void CThreadPool::OnTaskIdle(CWorkThread *pThread)
{
    pThread->SetThreadState(1);
}


void CThreadPool::GetTask(list<CBase*> &pTaskList,int nSize)
{
 {
  CAutoSynchronizer Syncher(m_TaskLock);
  int nIndex = 0;
  while(nIndex<nSize)
  {
         CBase *pBaseTask = NULL;
   pBaseTask = m_TaskList.front();
   if(pBaseTask)
   {
    pTaskList.push_back(pBaseTask);
    m_TaskList.pop_front();
   }
   nIndex++;
  }
 }
}

void CThreadPool::SetTask(list<CBase*> pTaskList) //归还任务
{
 {
  CAutoSynchronizer Syncher(m_TaskLock);
        list<CBase*>::iterator iter;
        for(iter = pTaskList.begin();iter != pTaskList.end(); ++iter)
        {
            CBase *pBaseTask = (*iter);
            AddTask(pBaseTask);
        }
 }
}

void CThreadPool::AddTask(CBase *pBaseTask)
{
 if(m_bStoped)
 { 
  cout<<"-----The threadpool is destroyed. /n";
  return;
 }
 CAutoSynchronizer Syncher(m_TaskLock);
 m_TaskList.push_back(pBaseTask);
}

int CThreadPool::GetTaskCount()
{
    printf("GetTaskCount开始/n");
 CAutoSynchronizer Syncher(m_TaskLock);
    printf("GetTaskCount结束/n");
    int nSize = m_TaskList.size();
 return nSize;
}

void CThreadPool::JoinWithAllThreads()
{
    for(int i = 0; i < m_ThreadList.Count();i++)
    {
        CWorkThread *pThread = NULL;
        pThread = (CWorkThread*)m_ThreadList[i];
        pThread->WaitFor();
    }
}

void CThreadPool::Execute(void)
{
 CWorkThread *pThread =  NULL;
 while(!GetTerminated())
 {
  Sleep(0.01);
        pThread = GetIdleThread();// 检查空闲线程队列

        if( pThread != NULL )
        {
            if( CheckNewTask() )  // 有新任务
   {
                if(pThread->GetThreadState() == 2)
                {
     int j = SjwResumeThread(pThread);
                    if(j > 0)
                    {
      pThread->SetThreadState(1);
                    }
     else
     {
      continue;
                    }
                }
                else
    {
     if(pThread->GetThreadState() != 1)
     {
      cout<<"线程状态等于="<<pThread->GetThreadState()<<endl;
      continue;
     }
                }
    list<CBase*> pTaskList;
    GetTask(pTaskList); // 取得一定数量的任务
    AddTaskToThread(pTaskList, pThread);// 把任务传入线程
    m_nLastTime = GetCurTicks();
    continue; // 继续循环
   }
   else
   {
             UpdateThread();
   }
        }
        if( pThread == NULL && m_ThreadList.Count() < m_nMaxSize )// 没有空闲线程了
        {
            CreateNewThread();// 创建新线程
            m_nLastTime = GetCurTicks();
            continue;// 继续循环
        }
        // 没有要处理的任务或者已经到达线程数的上限,进入超时等待
        if( WaitForTaskOrThreadTimeout() )
        {
            if( IncrIdleTime() > m_nTime )    // 系统空闲,计时
            {
                // 系统长时间处于空闲,销毁一定数量的空闲线程
                DecrIdleThread();
            }
        }
        else
        {
   printf("线程休息,原因是没有要处理的任务或者已经到达线程数的上限,已经超时结束/n");
   printf("%d/n",GetTaskCount());
            Sleep(0.1);
        }
    }

}

void CThreadPool::AddTaskToThread(list<CBase*> pTaskList,CWorkThread *pThread)
{
 pThread->SetTaskList(pTaskList);
 pThread->SetThreadState(0);
}

void CThreadPool::CreateNewThread()
{
    CAutoSynchronizer Syncher(m_ThreadLock);
    CWorkThread *hThread = new CWorkThread(this);
    m_ThreadList.Add(hThread);
    hThread->Run();
}

void CThreadPool::UpdateThread()
{
    CAutoSynchronizer Syncher(m_ThreadLock);
 for (int i = 0; i < m_ThreadList.Count(); i++)
    {
        CWorkThread *pThread = NULL;
        pThread=(CWorkThread*)m_ThreadList[i];
        if(pThread->GetThreadState() == 1)
        {
            int j = SjwSuspendThread(pThread);
            if(j >=0)
            {
                pThread->SetThreadState(2);
            }
        }
    }
}


unsigned int CThreadPool::GetThreadCount(void)
{
 CAutoSynchronizer Syncher(m_ThreadLock);
 return m_ThreadList.Count();
}

long CThreadPool::IncrIdleTime()
{
    return (GetCurTicks() - m_nLastTime);
}

void CThreadPool::DecrIdleThread()
{
    const int MAX_THREAD_WAIT_FOR_SECS = 10; // 线程池清空时最多等待时间(秒)
    const double SLEEP_INTERVAL = 0.5;      // 每次等待的时间间隔(秒)
    double nWaitSecs = 0;
    bool bFlag = false;
    int index = -1;
    // 通知线程退出
    {
        CAutoSynchronizer Syncher(m_ThreadLock);

        for (int i = m_ThreadList.Count()-1; i>= 0 && m_ThreadList.Count() > m_nSize; i--)
        {
            CWorkThread *pThread;
            pThread = (CWorkThread*)m_ThreadList[i];
            if(pThread->GetThreadState() == 2)
            {
                pThread->Terminate();
                bFlag = true;
                index = i;
                break;
            }
        }
    }
    // 等待线程退出
    while (nWaitSecs < MAX_THREAD_WAIT_FOR_SECS && bFlag)
    {
        if (m_ThreadList.Count() == 0) break;
        NanoSleep(SLEEP_INTERVAL, true);
        nWaitSecs += SLEEP_INTERVAL;
    }

    // 若等待超时,则强行杀死各线程
    if (m_ThreadList.Count() > 0 && bFlag)
    {
        CAutoSynchronizer Syncher(m_ThreadLock);
        CWorkThread *pThread;
        pThread = (CWorkThread*)m_ThreadList[index];
        pThread->Kill();
        m_ThreadList.Delete(index);
    }

}

bool CThreadPool::WaitForTaskOrThreadTimeout()
{
    Sleep(0.1);
    return true;
}

CWorkThread* CThreadPool::GetIdleThread()
{

    CAutoSynchronizer Syncher(m_ThreadLock);
    CWorkThread *pThread = NULL;
    for (int i = 0; i < m_ThreadList.Count(); i++)
    {
        if(((CWorkThread*)m_ThreadList[i])->GetThreadState() == 2 ||  ((CWorkThread*)m_ThreadList[i])->GetThreadState() == 1)
        {
            pThread=(CWorkThread*)m_ThreadList[i];
            break;
        }
    }
    return pThread;
}

bool CThreadPool::SetThreadTask(list<CBase*> pTaskList)
{
    CAutoSynchronizer Syncher(m_ThreadLock);
    bool bThread = false;
    CWorkThread *pThread = NULL;
    for (int i = 0; i < m_ThreadList.Count(); i++)
    {
        if(((CWorkThread*)m_ThreadList[i])->GetThreadState() == 2)
        {
            pThread=(CWorkThread*)m_ThreadList[i];
            int j = SjwResumeThread(pThread);
            if(j > 0)
            {
                pThread->SetThreadState(1);
            }
            else
            {
                continue;
            }
            m_ThreadList.Delete(i);
            AddTaskToThread(pTaskList, pThread);// 把任务传入线程
            bThread = true;
            break;
        }
        else if(((CWorkThread*)m_ThreadList[i])->GetThreadState() == 1)
        {
            pThread=(CWorkThread*)m_ThreadList[i];
            AddTaskToThread(pTaskList, pThread);// 把任务传入线程
            bThread = true;
            break;   
        }
    }
    return bThread;
}

bool CThreadPool::CheckNewTask()
{
    return !TaskIsEmpty();   
}

int CThreadPool::SjwSuspendThread(CWorkThread * pThread)
{
    return SuspendThread(pThread->GetHandle());
}

int CThreadPool::SjwResumeThread(CWorkThread * pThread)
{
    return ResumeThread(pThread->GetHandle());
}

bool CThreadPool::PoolFree()
{
    CAutoSynchronizer Syncher(m_TaskLock);
    if(m_TaskList.size() > 50)
    {
        return false;
    }
    return true;
}


CWorkThread::CWorkThread(const CThreadPool * _threadPool): m_pool(const_cast<CThreadPool *> (_threadPool)),m_pBaseTask(NULL)
,m_bThreadExit(false),m_bThreadExitFlag(false),m_nThreadState(0)
{
    m_Queue.clear();   
}

CWorkThread::~CWorkThread()
{
 if(m_pBaseTask != NULL)
    {
  delete m_pBaseTask;
        m_pBaseTask = NULL;
    }
 deque<CBase*>::iterator iter;
    for(iter = m_Queue.begin();iter != m_Queue.end();++iter)
    {
        CBase *pTemp = *iter;
        delete pTemp;
    }
}

void CWorkThread::Execute(void)
{
 while(!GetTerminated())
    {
        // 检查任务队列是否有任务要运行
        if( CheckTaskQueue() )                                                                                                                                                                                                                                                                                                       
  {
   if(m_nThreadState == 0)
   {
             // 队列中没有任务
    m_pool->OnTaskIdle(this); // 通知线程池,此线程已经空闲
   }
            if( WaitForTask())
                continue;// 继续循环
            else
               break;
        }
        else
        {
            // 有任务需要运行
   m_pBaseTask = GetTask(); // 取得新任务
            if(m_pBaseTask != NULL)
            {
                try
                {
                    while(!GetTerminated())
                    {
      int nRun = m_pBaseTask->Run(this->GetThreadId());
                        if(nRun == 0)
                        {
                            Sleep(0.02);
                            continue;
                        }
                        else if(nRun == 1)
                        {
                         break;
      }
      //break;
                    }
                   
                }
                catch(...)
                {

                }
    delete m_pBaseTask; // 任务执行完毕,删除此任务
    m_pBaseTask  = NULL;
            }

        }
    }
    m_bThreadExitFlag = true;
}

void CWorkThread::SetTaskList(list<CBase*> pTaskList)
{
    CAutoSynchronizer Syncher(m_Lock);
 list<CBase*>::iterator iter;
    for(iter = pTaskList.begin();iter != pTaskList.end();++iter)
    {
  m_Queue.push_back(*iter);
    }
 pTaskList.clear();
}

bool  CWorkThread::WaitForTask()
{
     if(!m_bThreadExit)
     {
  Sleep(0.1);
        return true;
     }
     else
        return false;
}


bool  CWorkThread::CheckTaskQueue()
{
 CAutoSynchronizer Syncher(m_Lock);
 return m_Queue.empty();
}

CBase* CWorkThread::GetTask()
{
   CBase *pBaseTask = NULL;
 {
        CAutoSynchronizer Syncher(m_Lock);
  pBaseTask = m_Queue.front();
        if(pBaseTask)
        {
            m_Queue.pop_front();
        }
 }
 return pBaseTask;
}

 

上面代码问题就是 线程池任务分配线程和工作者线程有死锁的现象,大家帮我看看,谢谢!!!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值