#include <atomic>
#include <iostream>
#include <unistd.h>
#include <queue>
using namespace std;
using callback = void(*)(void *);
class Task {
public:
Task(callback func, void *arg): func(func), arg(arg){}
void run() {func(arg);}
private:
callback func;
void *arg;
};
class ThreadPool {
public:
ThreadPool(uint32_t min, uint32_t max);
~ThreadPool();
void submitTask(Task *task);
bool hasTask();
private:
static void *manager(void *arg);
static void *worker(void *arg);
pthread_mutex_t queueMutex;
pthread_cond_t notEmpty;
queue<Task*> *taskQueue;
pthread_t *threads;
pthread_t manageThread;
uint32_t minThreadNum;
uint32_t maxThreadNum;
bool isShutdown;
};
bool ThreadPool::hasTask()
{
if (taskQueue->empty())
return false;
else
return true;
}
void ThreadPool::submitTask(Task *task)
{
pthread_mutex_lock(&queueMutex);
taskQueue->push(task);
pthread_mutex_unlock(&queueMutex);
pthread_cond_broadcast(¬Empty);
}
void *ThreadPool::worker(void *arg)
{
ThreadPool *pool = (ThreadPool *)arg;
Task *task;
while(!pool->isShutdown) {
pthread_mutex_lock(&pool->queueMutex);
while(pool->taskQueue->empty()) {
pthread_cond_wait(&pool->notEmpty, &pool->queueMutex);
}
task = pool->taskQueue->front();
pool->taskQueue->pop();
pthread_mutex_unlock(&pool->queueMutex);
task->run();
delete task;
}
pthread_exit(0);
}
void *ThreadPool::manager(void *arg)
{
pthread_exit(0);
}
ThreadPool::ThreadPool(uint32_t min, uint32_t max)
{
isShutdown = false;
minThreadNum = min;
maxThreadNum = max;
pthread_mutex_init(&queueMutex, NULL);
pthread_cond_init(¬Empty, NULL);
taskQueue = new queue<Task*>();
threads = new pthread_t[maxThreadNum];
pthread_t pthid;
for (int i = 0; i < minThreadNum; i++) {
pthread_create(&pthid, NULL, worker, this);
threads[i] = pthid;
}
pthread_create(&manageThread, NULL, manager, NULL);
}
ThreadPool::~ThreadPool()
{
isShutdown = true;
pthread_cond_broadcast(¬Empty);
delete [] threads;
delete taskQueue;
}
void taskFunc(void* arg)
{
int num = *(int*)arg;
printf("thread %ld is working, number = %d\n",
pthread_self(), num);
//sleep(1);
}
int main()
{
// 创建线程池
ThreadPool *pool = new ThreadPool(2, 4);
Task *task;
int *arg;
for (int i = 0; i < 100; ++i)
{
arg = new int(i);
task = new Task(taskFunc, arg);
pool->submitTask(task);
}
while (pool->hasTask()) {
sleep(1);
}
delete pool;
return 0;
}
C++实现简单线程池
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 频繁的分配和回收内存会严重降低程序的性能。原因在于默认的内存管理器是通用的、应用程序可能会以某种特定的方式使用内存...
- 一个简单的线程池,应该具备以下能力:1.能够有效的管理工作线程数量。(可以通过4个参数来管理,初始化线程数,最大线...