File size: 3,075 Bytes
68888be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "common/threads.h"

#include <algorithm>
#include <cstdlib>
#include <exception>

namespace hk {

static thread_local bool tl_in_pool = false;

ThreadPool::ThreadPool(int threads) {
    int n = std::max(1, threads) - 1;
    workers_.reserve((size_t)n);
    for (int i = 0; i < n; ++i) workers_.emplace_back([this] { worker_loop(); });
}

ThreadPool::~ThreadPool() {
    {
        std::lock_guard<std::mutex> lock(mu_);
        stop_ = true;
    }
    cv_work_.notify_all();
    for (auto& t : workers_) t.join();
}

void ThreadPool::run_chunks() {
    // called with mu_ unlocked
    while (true) {
        int64_t b, e;
        const std::function<void(int64_t, int64_t)>* fn;
        {
            std::lock_guard<std::mutex> lock(mu_);
            if (fn_ == nullptr || next_ >= n_) return;
            b = next_;
            e = std::min(n_, b + grain_);
            next_ = e;
            fn = fn_;
            ++active_;
        }
        // keep the first exception and rethrow it on the calling thread
        std::exception_ptr err;
        try {
            (*fn)(b, e);
        } catch (...) {
            err = std::current_exception();
        }
        {
            std::lock_guard<std::mutex> lock(mu_);
            if (err) {
                if (!error_) error_ = err;
                next_ = n_;  // stop handing out chunks
            }
            --active_;
            if (next_ >= n_ && active_ == 0) cv_done_.notify_all();
        }
    }
}

void ThreadPool::worker_loop() {
    tl_in_pool = true;
    uint64_t seen = 0;
    while (true) {
        {
            std::unique_lock<std::mutex> lock(mu_);
            cv_work_.wait(lock, [&] { return stop_ || generation_ != seen; });
            if (stop_) return;
            seen = generation_;
        }
        run_chunks();
    }
}

void ThreadPool::parallel_for(int64_t n, int64_t grain, const std::function<void(int64_t, int64_t)>& fn) {
    if (n <= 0) return;
    grain = std::max<int64_t>(1, grain);
    // small job, pool of one, or nested call
    if (workers_.empty() || n <= grain || tl_in_pool) {
        fn(0, n);
        return;
    }
    {
        std::lock_guard<std::mutex> lock(mu_);
        fn_ = &fn;
        n_ = n;
        grain_ = grain;
        next_ = 0;
        active_ = 0;
        error_ = nullptr;
        ++generation_;
    }
    cv_work_.notify_all();
    tl_in_pool = true;  // the caller participates; nested parallel_for inside fn stays serial
    run_chunks();
    tl_in_pool = false;
    std::unique_lock<std::mutex> lock(mu_);
    cv_done_.wait(lock, [&] { return next_ >= n_ && active_ == 0; });
    fn_ = nullptr;
    if (error_) {
        std::exception_ptr err = error_;
        error_ = nullptr;
        lock.unlock();
        std::rethrow_exception(err);
    }
}

ThreadPool& ThreadPool::global() {
    static ThreadPool pool([] {
        int n = (int)std::thread::hardware_concurrency();
        if (const char* env = std::getenv("HKIMI_THREADS")) n = std::atoi(env);
        return std::max(1, n);
    }());
    return pool;
}

}  // namespace hk