一种线程的使用模式,线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建于销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。
池化技术:以空间换时间
ThreadPool.hpp文件
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <unistd.h>
#include <pthread.h>
struct ThreadInfo
{
pthread_t tid;
std::string name;
};
static const int defaultnum = 5;
template<class T>
class ThreadPool
{
public:
void Lock()
{
pthread_mutex_lock(&mutex_);
}
void Unlock()
{
pthread_mutex_unlock(&mutex_);
}
void Wakeup()
{
pthread_cond_signal(&cond_);
}
void ThreadSleep()
{
pthread_cond_wait(&cond_,&mutex_);
}
bool IsQueueEmpty()
{
return tasks_.empty();
}
public:
ThreadPool(int num = defaultnum)
:threads_(num)
{
pthread_mutex_init(&mutex_, nullptr);
pthread_cond_init(&cond_, nullptr);
}
static void *HandlerTask(void *args)
{
ThreadPool<T> *tp = static_cast<ThreadPool<T>* >(args);
while(true)
{
tp->Lock();
while(tp->IsQueueEmpty())
{
tp->ThreadSleep();
}
T t = tp->Pop();
tp->Unlock();
t();
}
return nullptr;
}
void Start()
{
int num = threads_.size();
for(int i = 0; i < num; ++i)
{
threads_[i].name = "thread." + std::to_string(i + 1);
pthread_create(&(threads_[i].tid), nullptr, HandlerTask, this);
}
}
T Pop()
{
T t = tasks_.front();
tasks_.pop();
return t;
}
void Push(const T &t)
{
Lock();
tasks_.push(t);
Wakeup();
Unlock();
}
~ThreadPool()
{
pthread_mutex_destroy(&mutex_);
pthread_cond_destroy(&cond_);
}
private:
std::vector<ThreadInfo> threads_;
std::queue<T> tasks_;
pthread_mutex_t mutex_;
pthread_cond_t cond_;
};
Main.cpp
#include <iostream>
#include "ThreadPool.hpp"
#include "Task.hpp"
int main()
{
ThreadPool<Task>* tp = new ThreadPool<Task>(5);
tp->Start();
while(true)
{
// 1.构建任务
sleep(1);
// 2.交给线程处理
std::cout << "main thread is running..." << std::endl;
}
}
线程池的应用场景:
- 需要大量的线程来完成任务,且完成任务的时间比较短。WEB服务器完成网页请求这样的任务,使用线程池技术时非常合适的。因为单个任务小,而任务数量巨大,类似于一个热点网站的点击次数。但是对于长时间的任务,线程池的优势就不明显了。
- 对性能要求苛刻的应用,比如要求服务器迅速响应客户请求。
- 接受突发性的大量请求,但不至于使服务器因此产生大量线程的应用。

4840

被折叠的 条评论
为什么被折叠?



