-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
95 lines (70 loc) · 2.23 KB
/
Copy pathThreadPool.h
File metadata and controls
95 lines (70 loc) · 2.23 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <pthread.h>
#include <queue>
#include <cf/vec.h>
#pragma once
#define THREAD_POOL_SIZE 10
struct Task {
void (*func)(void*);
void* arg;
};
class ThreadPool {
private:
std::vector<pthread_t> workers;
std::queue<Task> taskQueue;
pthread_mutex_t queueMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t queueCond = PTHREAD_COND_INITIALIZER;
bool stop = false;
size_t numThreads;
// Worker thread function
static void* workerThread(void* arg) {
ThreadPool* pool = static_cast<ThreadPool*>(arg);
while (true) {
pthread_mutex_lock(&pool->queueMutex);
// Wait for a task
while (pool->taskQueue.empty() && !pool->stop) {
pthread_cond_wait(&pool->queueCond, &pool->queueMutex);
}
// Stop signal
if (pool->stop && pool->taskQueue.empty()) {
pthread_mutex_unlock(&pool->queueMutex);
break;
}
// Get task from queue
Task task = pool->taskQueue.front();
pool->taskQueue.pop();
pthread_mutex_unlock(&pool->queueMutex);
// Execute task
task.func(task.arg);
}
return nullptr;
}
public:
ThreadPool(size_t numThreads = THREAD_POOL_SIZE): numThreads(numThreads) {
for (size_t i = 0; i < numThreads; ++i) {
pthread_t thread;
pthread_create(&thread, nullptr, workerThread, this);
workers.push_back(thread);
}
}
void submit(void (*func)(void*), void* arg) {
pthread_mutex_lock(&queueMutex);
taskQueue.push(Task{func, arg});
pthread_cond_signal(&queueCond);
pthread_mutex_unlock(&queueMutex);
}
void shutdown() {
pthread_mutex_lock(&queueMutex);
stop = true;
// std::queue<Task>().swap(taskQueue);
pthread_cond_broadcast(&queueCond);
pthread_mutex_unlock(&queueMutex);
for (pthread_t& thread : workers) {
pthread_join(thread, nullptr);
}
}
~ThreadPool() {
shutdown();
pthread_mutex_destroy(&queueMutex);
pthread_cond_destroy(&queueCond);
}
};