-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththreadpool.cpp
More file actions
executable file
·53 lines (44 loc) · 1.13 KB
/
threadpool.cpp
File metadata and controls
executable file
·53 lines (44 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "threadpool.h"
#include "mutexlockguard.h"
MutexLock ThreadPool::mutex;
Condition ThreadPool::cond(mutex);
queue<SyncTask> ThreadPool::taskQueue;
ThreadPool::ThreadPool(int threadNum):threadNum(threadNum)
{
tid = (pthread_t*)malloc(sizeof(pthread_t) * threadNum);
for(int i=0;i<threadNum;i++)
pthread_create(&tid[i],NULL,threadFunc,NULL);
}
//线程回调函数
void *ThreadPool::threadFunc(void *data)
{
pthread_t tid = pthread_self();
SyncTask task;
while (1)
{
{
MutexLockGuard mutexLock(mutex);
while (taskQueue.size() == 0)
{
cond.wait();
}
//取出一个任务并处理之
task = std::move(taskQueue.front());
taskQueue.pop();
}
CHEN_LOG(DEBUG,"tid %lu run", tid);
task(); /** 执行任务 */
CHEN_LOG(DEBUG,"tid:%lu idle", tid);
}
return (void*)0;
}
void ThreadPool::AddTask(SyncTask task)
{
MutexLockGuard mutexLock(mutex);
taskQueue.push(std::move(task));
cond.notify();
}
int ThreadPool::getTaskSize()
{
return taskQueue.size();
}