编写程序准备知识
(1)pthread_mutex_t CThreadPool::m_pthreadMutex = PTHREAD_MUTEX_INITIALIZER;(互斥锁初始化)
(2)pthread_cond_t CThreadPool::m_pthreadCond = PTHREAD_COND_INITIALIZER;(条件锁初始化)
(3) pthread_mutex_lock(&m_pthreadMutex);(加锁)
(4)pthread_mutex_unlock(&m_pthreadMutex);(解锁)
(5)pthread_cond_signal(&m_pthreadCond);(发送条件锁信号)
(6)pthread_cond_broadcast(&m_pthreadCond);(广播条件锁信号)
(7)pthread_mutex_destroy(&m_pthreadMutex);(销毁锁)
(8)pthread_cond_destroy(&m_pthreadCond);(销毁条件锁)
编写头文件
thread_pool.h文件
#ifndef __THREAD_POOL_H
#define __THREAD_POOL_H
#include <vector>
#include <string>
#include <pthread.h>
using namespace std;
/*执行任务的类:设置任务数据并执行*/
class CTask {
protected:
string m_strTaskName; //任务的名称
void* m_ptrData; //要执行的任务的具体数据
public:
CTask() = default;
CTask(string &taskName)
: m_strTaskName(taskName)
, m_ptrData(NULL) {}
virtual int Run() = 0;
void setData(void* data); //设置任务数据
virtual ~CTask() {}
};
/*线程池管理类*/
class CThreadPool {
private:
static vector<CTask*> m_vecTaskList; //任务列表
static bool shutdown; //线程退出标志
int m_iThreadNum; //线程池中启动的线程数
pthread_t *pthread_id;
static pthread_mutex_t m_pthreadMutex; //线程同步锁
static pthread_cond_t m_pthreadCond; //线程同步条件变量
protected:
static void* ThreadFunc(void *threadData); //新线程的线程回调函数
static int MoveToIdle(pthread_t tid); //线程执行结束后,把自己放入空闲线程中
static int MoveToBusy(pthread_t tid); //移入到忙碌线程中去
int Create(); //创建线程池中的线程
public:
CThreadPool(int threadNum);
int AddTask(CTask *task); //把任务添加到任务队列中
int StopAll(); //使线程池中的所有线程退出
int getTaskSize(); //获取当前任务队列中的任务数
};
#endif
编写cpp文件
thread_pool.cpp文件
#include "thread_pool.h"
#include <cstdio>
void CTask::setData(void* data) {
m_ptrData = data;
}
//静态成员初始化
vector<CTask*> CThreadPool::m_vecTaskList;
bool CThreadPool::shutdown = false;
pthread_mutex_t CThreadPool::m_pthreadMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t CThreadPool::m_pthreadCond = PTHREAD_COND_INITIALIZER;
//线程管理类构造函数
CThreadPool::CThreadPool(int threadNum) {
this->m_iThreadNum = threadNum;
printf("I will create %d threads.\n", threadNum);
Create();
}
//线程回调函数
void* CThreadPool::ThreadFunc(void* threadData) {
pthread_t tid = pthread_self();
while (1)
{
pthread_mutex_lock(&m_pthreadMutex);
//如果队列为空,等待新任务进入任务队列
while (m_vecTaskList.size() == 0 && !shutdown)
pthread_cond_wait(&m_pthreadCond, &m_pthreadMutex);
//关闭线程
if (shutdown)
{
pthread_mutex_unlock(&m_pthreadMutex);
printf("[tid: %lu]\texit\n", pthread_self());
pthread_exit(NULL);
}
printf("[tid: %lu]\trun: ", tid);
vector<CTask*>::iterator iter = m_vecTaskList.begin();
//取出一个任务并处理之
CTask* task = *iter;
if (iter != m_vecTaskList.end())
{
task = *iter;
m_vecTaskList.erase(iter);
}
pthread_mutex_unlock(&m_pthreadMutex);
task->Run(); //执行任务
printf("[tid: %lu]\tidle\n", tid);
}
return (void*)0;
}
//往任务队列里添加任务并发出线程同步信号
int CThreadPool::AddTask(CTask *task) {
pthread_mutex_lock(&m_pthreadMutex);
m_vecTaskList.push_back(task);
pthread_mutex_unlock(&m_pthreadMutex);
pthread_cond_signal(&m_pthreadCond);
return 0;
}
//创建线程
int CThreadPool::Create() {
pthread_id = new pthread_t[m_iThreadNum];
for (int i = 0; i < m_iThreadNum; i++)
pthread_create(&pthread_id[i], NULL, ThreadFunc, NULL);
return 0;
}
//停止所有线程
int CThreadPool::StopAll() {
//避免重复调用
if (shutdown)
return -1;
printf("Now I will end all threads!\n\n");
//唤醒所有等待进程,线程池也要销毁了
shutdown = true;
pthread_cond_broadcast(&m_pthreadCond);
//清楚僵尸
for (int i = 0; i < m_iThreadNum; i++)
pthread_join(pthread_id[i], NULL);
delete[] pthread_id;
pthread_id = NULL;
//销毁互斥量和条件变量
pthread_mutex_destroy(&m_pthreadMutex);
pthread_cond_destroy(&m_pthreadCond);
return 0;
}
//获取当前队列中的任务数
int CThreadPool::getTaskSize() {
return m_vecTaskList.size();
}
运行原理图
使用C++库实现线程池(多线程,互斥锁)
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter(0); //定义一个全局变量,当作计数器用于累加
std::mutex mtx; // 用于保护counter的互斥锁
void thrfunc()
{
for (int i = 0; i < 10000; ++i)
{
if (mtx.try_lock())// 互斥锁上锁
{
++counter; //计数器累加
mtx.unlock(); //互斥锁解锁
}
else std::cout << "try_lock false\n" ;
}
}
int main(int argc, const char* argv[])
{
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(thrfunc); //启动10个线程
for (auto& th : threads) th.join(); //等待10个线程结束
std::cout << "count to " << counter << " successfully \n";
return 0;
}