文章目录
一、线程池
线程池:一种线程使用模式。线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。
线程池的应用场景:
1.需要大量的线程来完成任务,且完成任务的时间比较短。 WEB服务器完成网页请求这样的任务,使用线程池技术是非常合适的。因为单个任务小,而任务数量巨大,你可以想象一个热门网站的点击次数。 但对于长时间的任务,比如一个Telnet连接请求,线程池的优点就不明显了。因为Telnet会话时间比线程的创建时间大多了。
2.对性能要求苛刻的应用,比如要求服务器迅速响应客户请求。
3.接受突发性的大量请求,但不至于使服务器因此产生大量线程的应用。突发性大量客户请求,在没有线程池情况下,将产生大量线程,虽然理论上大部分操作系统线程数目最大值不是问题,短时间内产生大量线程可能使内存到达极限,出现错误.
线程池的种类:
线程池示例:
1.创建固定数量线程池,循环从任务队列中获取任务对象,
2.获取到任务对象后,执行任务对象中的任务接口
Thread.hpp
以下是自己封装实现的线程
#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <cassert>
#include <pthread.h>
namespace ThreadNs
{
typedef std::function<void *(void *)> func_t;
const int num = 1024;
class Thread
{
private:
static void *start_routine(void *args)
{
Thread *td = static_cast<Thread *>(args);
return td->callback();
}
public:
Thread()
{
char buffer[num];
snprintf(buffer, sizeof buffer, "thread-%d", threadnum++);
_name = buffer;
}
void start(func_t func, void *args)
{
_func = func;
_args = args;
int n = pthread_create(&_tid, nullptr, start_routine, this);
}
void join()
{
int n = pthread_join(_tid, nullptr);
assert(n == 0);
(void)n;
}
std::string threadname()
{
return _name;
}
void *callback()
{
return _func(_args);
}
~Thread()
{
}
private:
std::string _name;
void *_args;
func_t _func;
pthread_t _tid;
static int threadnum;
};
int Thread::threadnum = 1;
}
LockGuard.hpp
以下是自己封装实现的RAII风格的锁
#pragma once
#include <cassert>
#include <pthread.h>
class Mutex
{
public:
Mutex(pthread_mutex_t *lock_p = nullptr)
: _lock_p(lock_p)
{
}
void lock()
{
if (_lock_p)
{
int n = pthread_mutex_lock(_lock_p);
assert(n == 0);
(void)n;
}
}