blob: f19032ee0142d769d8e0fc03208faecc06c16696 (
plain)
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
|
#include <mbgl/util/threadpool.hpp>
#include <mbgl/util/std.hpp>
#include <thread>
#include <memory>
using namespace mbgl::util;
std::unique_ptr<Threadpool> mbgl::util::threadpool = std::make_unique<Threadpool>(std::thread::hardware_concurrency());
Threadpool::Threadpool(int max_workers)
: max_workers(max_workers) {
}
void Threadpool::add(Callback callback, void *data) {
if (worker_count < max_workers) {
worker_count++;
workers.emplace_front(*this);
}
pthread_mutex_lock(&mutex);
tasks.push(std::make_pair(callback, data));
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condition);
}
Threadpool::Worker::Worker(Threadpool& pool)
: pool(pool) {
pthread_create(&thread, nullptr, loop, (void *)this);
}
Threadpool::Worker::~Worker() {
pthread_cancel(thread);
}
void *Threadpool::Worker::loop(void *ptr) {
Worker *worker = static_cast<Worker *>(ptr);
Threadpool& pool = worker->pool;
pthread_mutex_lock(&pool.mutex);
while (true) {
if (pool.tasks.size()) {
Threadpool::Task task = pool.tasks.front();
pool.tasks.pop();
pthread_mutex_unlock(&pool.mutex);
task.first(task.second);
pthread_mutex_lock(&pool.mutex);
} else {
pthread_cond_wait(&pool.condition, &pool.mutex);
}
}
return nullptr;
}
|