本文主要介绍了C++实现一个简单的线程池的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
一、设计
线程池应该包括
- 保存线程的容器,保存任务的容器。
- 为了能保证避免线程对任务的竞态获取,需要对任务队列进行加锁。
- 为了使得工作线程感知任务的到来,需要使用条件变量来唤醒工作线程。
- 任务容器中的任务管理。
- 任务的处理API。
二、参数选择
使用数组存放线程,链表存放任务。
三、类设计
线程池类
template<typename T>
class threadpool
{
public:
threadpool(int thread_num,int max_request);
~threadpool();
bool append(T* request); // 在任务队列中添加任务
private:
static void worker(void* arg);
void run();
private:
int m_thread_num; // 线程池中的线程数
int m_max_request; // 任务队列最大保存的任务数
pthread_t *m_threads; // 保存线程的容器
std::list<T*>m_queuework; // 保存任务的链表
sem m_sem; // 通知工作线程任务到来
lock m_locker; // 互斥访问任务队列
};
构造函数
template<typename T>
threadpool<T>::threadpool(int thread_num,int max_request):m_thread_num(thread_num),m_max_request(max_request)
{
if(thread_num <=0 || max_request <= 0) throw std::exception();
m_threads = new pthread_t[thread_num];
if(!m_threads) throw std::exception();
for(int i = 0;i < thread_num;++i)
{
// 创建线程
if(pthread_create(m_threads + i, NULL,worker,this)!=0)
{
delete[] m_threads;
throw std::exception();
}
// 分离线程
if(pthread_detach(m_threads[i]))
{
delete[] m_threads;
throw std::exception();
}
}
}
析构函数
template<typename T>
threadpool<T>::~threadpool()
{
delete[] m_trheads;
}
添加任务函数
template<typename T>
bool threadpool<T>::append(T* request)
{
m_locker.lock();
if(m_queuework.size() > m_max_request)
{
m_locker.unlock();
return false;
}
m_queuework.push_back(request);
m_locker.unlock();
m_sem.post();
return true;
}
任务处理函数
template<typename T>
void* threadpool<T>::worker(void*arg)
{
threadpool* pool = (threadpool*)arg;
pool->run();
return pool;
}
template<typename T>
void threadpool<T>::run()
{
while(true)
{
m_sem.wait();
m_locker.lock();
if(m_queuework.empty())
{
m_locker.unlock();
continue;
}
T* request = m_queuework.front();
m_queuework.pop_front();
m_locker.unlock();
request.process(); // 具体任务的处理业务
}
}
到此这篇关于C++实现一个简单的线程池的示例代码的文章就介绍到这了,更多相关C++ 线程池内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:C++实现一个简单的线程池的示例代码


猜你喜欢
- C语言qsort()函数的使用方法详解 2023-04-26
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- Easyx实现扫雷游戏 2023-02-06
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- ubuntu下C/C++获取剩余内存 2023-09-18
- C语言详解float类型在内存中的存储方式 2023-03-27
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- Qt计时器使用方法详解 2023-05-30
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C++ 数据结构超详细讲解顺序表 2023-03-25