c++实现的线程池

下面这个线程池是我在工作中用到过的,原理还是建立一个任务队列,让多个线程互斥的在队列中取出任务,然后执行,显然,队列是要加锁的

环境:ubuntu linux

文件名:locker.h

#ifndef LOCKER_H_
#define LOCKER_H_

#include "pthread.h"


class locker
{
public:
	locker();
	virtual ~locker();

	bool lock();
	void unlock();

private:
    pthread_mutex_t     m_mutex;
};

#endif /* LOCKER_H_ */

文件名:locker.cpp

#include "locker.h"

locker::locker()
{
    pthread_mutex_init(&m_mutex, 0);
}

locker::~locker()
{
    pthread_mutex_destroy(&m_mutex);
}

bool locker::lock()
{
    if(0 == pthread_mutex_lock(&m_mutex))
        return true;
    return false;
}

void locker::unlock()
{
    pthread_mutex_unlock(&m_mutex);
}
文件名:task_list.h

#ifndef TASK_LIST_H_
#define TASK_LIST_H_

#include "list"
#include "locker.h"
#include "netinet/in.h"
#include "semaphore.h"

using namespace std;

typedef void* (*THREAD_FUNC)(void*);

// 线程池中运行的任务,对于下行任务,sin中包含目的地址信息
// parm0指向发出数据的对象,parm1指向数据,parm2为数据的长度
typedef struct
{
	THREAD_FUNC func;
	void* parm0;
	void* parm1;
	void* parm2;
} task_info;

typedef list<task_info*> TASK_LIST;
typedef list<task_info*>::iterator PTASK_LIST;

class task_list
{
public:
	task_list();
	virtual ~task_list();

	void append_task(task_info* tsk);
	task_info* fetch_task();

private:
	TASK_LIST m_tasklist;
	locker m_lk;
	sem_t m_sem;
};

#endif /* TASK_LIST_H_ */
文件名:task_list.cpp

#include "task_list.h"


task_list::task_list()
{
    // Init Semaphore
    sem_init(&m_sem, 0, 0);
    m_tasklist.clear();
}

task_list::~task_list()
{
    while(!m_tasklist.empty())
    {
        task_info* tr = m_tasklist.front();
        m_tasklist.pop_front();

        if(tr)
            delete tr;
    }
    // Destroy Semaphore
    sem_destroy(&m_sem);
}

void task_list::append_task(task_info* tsk)
{
    // Lock before Modify the list
    m_lk.lock();
    m_tasklist.push_back(tsk);
    m_lk.unlock();
    // Increase the Semaphore
    sem_post(&m_sem);
}

task_info* task_list::fetch_task()
{
    task_info* tr = NULL;

    sem_wait(&m_sem);

    m_lk.lock();
    tr = m_tasklist.front();
    m_tasklist.pop_front();
    m_lk.unlock();

    return tr;
}
文件名:thread_pool.h

#ifndef THREAD_POOL_H_
#define THREAD_POOL_H_

#include "task_list.h"
#include "pthread.h"

#define DEFAULT_THREAD_COUNT    4
#define MAXIMUM_THREAD_COUNT    1000


class thread_pool
{
public:
	thread_pool();
	virtual ~thread_pool();

	int  create_threads(int n = DEFAULT_THREAD_COUNT);
	void delete_threads();

	void set_tasklist(task_list* plist);
	void del_tasklist();

protected:
    static void* thread_func(void* parm);
    task_info* get_task();

private:
    int             m_thread_cnt;
    pthread_t       m_pids[MAXIMUM_THREAD_COUNT];

    task_list*      m_tasklist;
};

#endif /* THREAD_POOL_H_ */

文件名:thread_pool.cpp

#include "thread_pool.h"

thread_pool::thread_pool()
{
	m_thread_cnt = 0;
	m_tasklist = NULL;
}

thread_pool::~thread_pool()
{
	delete_threads();
}

task_info* thread_pool::get_task()
{
	task_info* tr;

	if (m_tasklist)
	{
		tr = m_tasklist->fetch_task();
		return tr;
	}

	return NULL;
}

void* thread_pool::thread_func(void* parm)
{
	thread_pool *ptp = static_cast<thread_pool*> (parm);
	task_info *task;

	while (true)
	{
		task = ptp->get_task();
		if (task)
		{
			(*task->func)(task);
			//delete task; //func负责释放task_info
		}
	}
	return NULL;
}

int thread_pool::create_threads(int n)
{
	if (n > MAXIMUM_THREAD_COUNT)
		n = MAXIMUM_THREAD_COUNT;

	delete_threads();

	for (int i = 0; i < n; i++)
	{
		int ret = pthread_create(&m_pids[i], NULL, thread_func, (void*) this);
		if (ret != 0)
			break;
		m_thread_cnt++;
	}

	return m_thread_cnt;
}

void thread_pool::delete_threads()
{
	for (int i = 0; i < m_thread_cnt; i++)
	{
		void* retval;

		pthread_cancel(m_pids[i]);
		pthread_join(m_pids[i], &retval);
	}
	m_thread_cnt = 0;
}

void thread_pool::set_tasklist(task_list* plist)
{
	m_tasklist = plist;
}

void thread_pool::del_tasklist()
{
	m_tasklist = NULL;
}
文件名:test.cpp

#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "task_list.h"
#include "thread_pool.h"


void* fun(void *parm)
{
	task_info* ptk = (task_info*)parm;
	pid_t tid = pthread_self();
	int count = (int)ptk->parm0;
	printf("count=%d, tid=%d\n", count, tid);
	return NULL;
}

int main()
{
	int count = 0;
	thread_pool tp;
	task_list tl;

	tp.create_threads(4 - 1);
	tp.set_tasklist(&tl);

	while (1)
	{
		task_info* pti = NULL;
		pti = (task_info *) malloc(sizeof(task_info));
		pti->func = fun;
		pti->parm0 = (void *)count;
		tl.append_task(pti);
		count++;
		sleep(2);
	}
//	printf("hello,world\n");
	return 0;
}

编译运行,我是用ecplise建立的automake工程,所以只要修改一下Makefile.am就可以编译成功了

文件名:Makefile.am

bin_PROGRAMS=test
test_SOURCES=test.cpp locker.h locker.cpp \
 							task_list.h task_list.cpp \
 							thread_pool.h thread_pool.cpp
test_LDADD=-lpthread

执行结果:

count=0, tid=-1219888272
count=1, tid=-1219888272
count=2, tid=-1228280976
count=3, tid=-1236673680
count=4, tid=-1219888272
count=5, tid=-1228280976
count=6, tid=-1236673680
count=7, tid=-1219888272
count=8, tid=-1228280976
count=9, tid=-1236673680

转载请注明出处: http://blog.csdn.net/liujian0616/article/details/7954381

<think>好的,我现在需要帮用户解决如何用C++实现线程池的问题。首先,我得回顾用户提供的引用内容,看看里面有哪些关键点。引用1到4提到了不同的实现方法,比如使用vector存储线程、构造函数中的初始化、任务队列的管理,还有析构函数中的资源回收。用户需要具体的代码示例和实现方法,所以我得把这些信息整合起来。 首先,线程池的基本组成部分包括任务队列、工作线程和管理线程。引用3提到使用TaskQueue来管理任务,工作线程从队列中取任务执行。构造函数里初始化线程数组和管理线程,析构函数负责安全关闭。这点很重要,用户可能需要知道如何正确释放资源,避免内存泄漏。 然后,引用2中的构造函数示例展示了如何根据硬件并发数创建线程,并在lambda函数中处理任务循环。这可以帮助用户理解工作线程的逻辑结构。同时,引用4提到销毁时的冲突问题,需要处理队列和线程的同步,可能需要互斥锁和条件变量来管理。 接下来,我需要考虑代码的结构。通常线程池需要一个任务队列,用互斥锁保护,条件变量来通知线程有新任务。工作线程循环等待任务,处理完任务后继续等待。管理线程可能用于动态调整线程数量,如引用3中的例子,但用户可能只需要基础实现,所以可以先简化这部分。 用户可能需要一个简单但完整的示例,所以我要确保代码涵盖必要的部分:任务提交、线程启动、任务处理、资源回收。同时,需要解释关键部分,比如如何停止线程池,如何处理未完成的任务。 可能的问题点包括:线程安全的任务队列、正确使用条件变量避免死锁、在析构函数中通知所有线程退出。引用4提到了clear和shutdown的冲突,所以需要确保在停止时先清空队列,再通知线程退出。 现在,我需要将这些元素整合成一个示例代码。使用C++11或更高版本的特性,比如std::thread、std::mutex、std::condition_variable。任务队列可以用std::queue,用lambda函数作为任务类型。构造函数中创建一定数量的工作线程,每个线程循环等待任务。添加任务时,锁定互斥锁,将任务加入队列,然后通知一个线程。析构函数设置停止标志,通知所有线程,并join它们。 还需要处理异常情况,比如线程池已停止时不能再添加任务。用户可能想知道如何扩展功能,比如动态调整线程数量,但基础示例可能不需要这些,可以作为相关问题提出。 最后,检查代码是否符合引用中的最佳实践,比如使用RAII管理资源,正确锁定作用域,避免死锁。确保示例代码简洁,易于理解,同时覆盖关键实现步骤。</think>### C++线程池实现方法详解 #### 一、基本结构 线程池核心包含任务队列、工作线程组、同步机制三部分。以下为实现要点: 1. **任务队列**:使用`std::queue<std::function<void()>>`存储待执行任务 2. **线程管理**:`std::vector<std::thread>`维护工作线程组 3. **同步机制**:`std::mutex`与`std::condition_variable`实现线程间通信 #### 二、完整代码示例 ```cpp #include <vector> #include <thread> #include <queue> #include <mutex> #include <condition_variable> #include <functional> #include <future> class ThreadPool { public: explicit ThreadPool(size_t threads = std::thread::hardware_concurrency()) : stop(false) { for(size_t i = 0; i < threads; ++i) { workers.emplace_back([this] { while(true) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); }); if(this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } }); } } template<class F, class... Args> auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>( std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); if(stop) throw std::runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([task](){ (*task)(); }); } condition.notify_one(); return res; } ~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for(std::thread &worker : workers) if(worker.joinable()) worker.join(); } private: std::vector<std::thread> workers; std::queue<std::function<void()>> tasks; std::mutex queue_mutex; std::condition_variable condition; bool stop; }; ``` #### 三、实现要点解析 1. **线程初始化**:构造函数中根据硬件并发数创建线程组,每个线程执行任务循环[^2] 2. **任务提交**:`enqueue`方法支持任意可调用对象,返回`std::future`获取异步结果 3. **任务执行**:工作线程通过条件变量唤醒,获取任务后释放锁执行[^3] 4. **安全停止**:析构函数先设置停止标志,再唤醒所有线程等待退出[^4] #### 四、使用示例 ```cpp #include <iostream> int main() { ThreadPool pool(4); for(int i = 0; i < 8; ++i) { pool.enqueue([i] { std::cout << "Task " << i << " executed by thread " << std::this_thread::get_id() << std::endl; }); } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值