c++实现带锁的线程池类

本文介绍了一个C++实现的线程池类,包括`ILock`接口、`critical_lock`互斥锁类和`scope_lock`智能锁类,以及`ThreadPool`线程池类。线程池类使用了互斥锁和信号量来管理任务队列,确保线程安全。此外,还展示了如何创建`Response`类来执行任务并调用回调函数。在测试的`main`函数中,创建了一个线程池实例,并提交了一个任务到线程池进行处理。
摘要由CSDN通过智能技术生成

话不多说上代码:

线程锁类:

#pragma once

#include <pthread.h>
#include <unistd.h>

namespace lock_summary
{
  class ILock
  {
    public:
      ILock(){}
      virtual ~ILock(){}

    public:
      virtual void lock() = 0;
      virtual void unlock() = 0;
  };

  class critical_lock : public ILock
  {
    public:
      critical_lock();
      ~critical_lock();

    public:
      void lock();
      void unlock();

    public:
      pthread_mutex_t m_cs;
  };

  class scope_lock
  {
    public:
      scope_lock(ILock* plock_entity);
      ~scope_lock(void);

    public:
      void lock();
      void unlock();

    private:
      ILock* m_pLock;
  };
}
#include "lock.h"

using namespace lock_summary;

critical_lock::critical_lock()
{
  //默认用非递归锁
  pthread_mutex_init(&m_cs, NULL);
}

critical_lock::~critical_lock()
{
  pthread_mutex_destroy(&m_cs);
}

void critical_lock::lock()
{
  pthread_mutex_lock(&m_cs);
}

void critical_lock::unlock()
{
  pthread_mutex_unlock(&m_cs);
}

//没有直接使用Mutex,而是封装了一层,防止忘记解锁
scope_lock::scope_lock(ILock* plock_entity)
{
  m_pLock = plock_entity;
  lock();
}

scope_lock::~scope_lock(void)
{
  unlock();
}

void scope_lock::lock()
{
  if (m_pLock != NULL)
  {
    m_pLock->lock();
  }
}

void scope_lock::unlock()
{
  if (m_pLock != NULL)
  {
    m_pLock->unlock();
  }
}

 线程池类:

#pragma once

#include <list>
#include "lock.h"

#include <pthread.h>
#include <semaphore.h>
#include <errno.h>

using namespace std;

namespace base
{
  class Runable
  {
  public:
    virtual ~Runable(){};
    virtual void run() = 0;
  };

  class ThreadPool
  {
  public:
    ThreadPool(void);
    ~ThreadPool(void);

    int start(int threadNum);//初始化一个线程池
    void execTask();//执行任务
    void runInThread(Runable* runobj);//入任务队列
    static void* _threadWork(void* pArgs);

  private: 
    list<Runable* > _taskQueue;
    lock_summary::critical_lock _crclLock;//任务队列锁
    sem_t _mSignal; 
  };
}
#include "ThreadPool.h"

#include <assert.h>

using namespace base;

ThreadPool::ThreadPool(void)
{
  sem_init(&_mSignal,0,0);
}

ThreadPool::~ThreadPool(void)
{
  sem_destroy(&_mSignal);
}

int ThreadPool::start(int threadNum)
{
  if (threadNum <= 0)
  {
    return -1;
  }
  for(int i=0; i<threadNum; i++) 
  {
    pthread_t tid;
    pthread_attr_t threadAttr;
    pthread_attr_init(&threadAttr);
    //线程属性设置
    pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
    pthread_attr_setstacksize(&threadAttr, 1024*1024*5);// 设置线程栈大小

    if(pthread_create(&tid, &threadAttr, ThreadPool::_threadWork, (void *)this) != 0)
      return -1;
  }
  return 0;
}

void* ThreadPool::_threadWork(void* pArgs)
{
  ThreadPool* pThis = (ThreadPool*)pArgs;
  pThis->execTask();
  return NULL;
}

void ThreadPool::execTask()
{
  while(1) 
  {
    //所有线程阻塞中,等待一个唤醒信号
    int ret;
    do{
      ret = sem_wait(&_mSignal);
    }while(ret == -1 && errno == EINTR);

    Runable* p = NULL;
    lock_summary::scope_lock lock(&_crclLock);
    if(_taskQueue.size() > 0)
    {
      p = _taskQueue.front();
      _taskQueue.pop_front();
    }
    lock.unlock();//提前让出队列操作权
    if( p!= NULL)
    {
      p->run();
      delete p;
    }
  }
  return;
}

void ThreadPool::runInThread(Runable* runobj)
{
  assert(runobj != NULL);
  {
    lock_summary::scope_lock lock(&_crclLock);
    _taskQueue.push_back(runobj);
    // 唤醒一个线程
    sem_post(&_mSignal);
  }
}

 线程池服务管理类

#ifndef RESPONSE__H_
#define RESPONSE__H_

#include <iostream>
#include "ThreadPool.h"

typedef void (*pfun)(char* sipMsg, int iresult, void* appData);

class Response : public base::Runable
{
public:
  Response(char* msg, pfun pf)
    :_msg(msg), _pFun(pf)
  {

  }
  virtual void run()
  {
    ServerThreadProc(_msg, _pFun);
  }
  void ServerThreadProc(char* message, pfun method);

private:
  char* _msg;
  pfun _pFun;
};

#endif
#include "Response.h"

void Response::ServerThreadProc(char* message, pfun method)
{
  method(message,1,NULL);
  printf("ServerThreadProc is leave.\n");
}

测试main函数

#include "Response.h"

#define MAXTHREADNUM   5

void test(char* sipMsg, int iresult, void* appData)
{
  printf("test into.\n");
  while(iresult)
  {
    printf("%s\n",sipMsg);
    if(appData != NULL)
    {
      sleep(1);
      cout<<"wait moment.";
    }
    iresult--;
  }
}

int main()
{
  base::ThreadPool thp;
  thp.start(MAXTHREADNUM);
  char msg[] = "this is a massage.";
  Response* res = new Response(msg,test);
  // Runable res = new Response(msg,test);
  thp.runInThread(res);
  
  cout<<"main exit."<<endl;
  sleep(3);//等待线程执行结果
  return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值