摘要:本文使用C++实现了一个单例的线程池,创建8个线程,可以执行相应的任务。
#include <iostream>
#include <thread>
#include <semaphore.h>
#include <mutex>
#include <queue>
#include <list>
class TaskBase{
public:
virtual void DoWork() = 0;
};
class downloadTask: public TaskBase{
public:
void DoWork() override{
std::cout << "downloadTask thread id=" << std::this_thread::get_id() << std::endl;
}
};
class ThreadPool{
public:
static ThreadPool& getInstance();
void append(TaskBase* task);
~ThreadPool();
private:
ThreadPool(int threadNum = 8);
ThreadPool(const ThreadPool&);
ThreadPool& operator = (const ThreadPool&);
static void* worker(void* arg);
void run();
private:
static ThreadPool pInstance;
std::queue<TaskBase*> m_workQueue;
std::mutex m_lock;
sem_t m_sem;
std::vector<std::thread*> m_threadList;
bool m_is_stop = true;
};
ThreadPool ThreadPool::pInstance;
ThreadPool& ThreadPool::getInstance(){
return pInstance;
}
ThreadPool::ThreadPool(int threadNum){
sem_init(&m_sem, 0, 0);
for(int i = 0; i < threadNum; i++){
std::thread *t = new std::thread(worker, this);
t->detach();
m_threadList.push_back(t);
std::cout << "create thread id=" << i + 1 << std::endl;
}
}
ThreadPool::~ThreadPool(){
m_is_stop = false;
sem_destroy(&m_sem);
for(int i = 0; i < m_threadList.size(); i++){
delete m_threadList[i];
}
}
void* ThreadPool::worker(void* arg){
ThreadPool* pool = (ThreadPool*)arg;
pool->run();
return pool;
}
void ThreadPool::append(TaskBase* task){
m_lock.lock();
m_workQueue.push(task);
m_lock.unlock();
sem_post(&m_sem);
std::cout << "append task" << std::endl;
}
void ThreadPool::run(){
//每一个线程的消息循环
while(m_is_stop){
sem_wait(&m_sem);
m_lock.lock();
TaskBase* task = m_workQueue.front();
m_workQueue.pop();
m_lock.unlock();
task->DoWork();
delete task;
}
}
#define threadPool ThreadPool::getInstance()
int main(){
std::cout << "Threads create successfully!" << std::endl << std::endl;
TaskBase *task = new downloadTask();
threadPool.append(task);
threadPool.append(task);
threadPool.append(task);
threadPool.append(task);
threadPool.append(task);
threadPool.append(task);
threadPool.append(task);
return 0;
}
运行结果: