ThreadPool.h 6.79 KB
Newer Older
1
2
3
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

4
5
6
7

/* heavily modified */


8
9
10
11
12
13
14
15
16
17
18
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include "error.h"

19

20
21
class ThreadPool {
public:
Damien Leroux's avatar
Damien Leroux committed
22
    ThreadPool(size_t, std::unordered_map<std::thread::id, std::vector<std::string>>*);
23
24
25
26
    template<class F, class... Args>
    auto enqueue(F&& f, Args&&... args) 
        -> std::future<typename std::result_of<F(Args...)>::type>;
    ~ThreadPool();
27
28
29

    void set_title(const std::string& s)
    {
Damien Leroux's avatar
Damien Leroux committed
30
        std::lock_guard<std::mutex> lock(title_mutex);
31
32
33
        title = s;
    }

34
35
36
37
38
39
    const std::string& get_title()
    {
        std::lock_guard<std::mutex> lock(title_mutex);
        return title;
    }

40
41
42
43
private:
    // need to keep track of threads so we can join them
    std::vector< std::thread > workers;
    // the task queue
Damien Leroux's avatar
Damien Leroux committed
44
    std::queue<std::function<void()>> tasks;
45
46
47
48
49
50
51
52
53
54
    
    // synchronization
    std::mutex queue_mutex;
    std::condition_variable condition;
	std::atomic_bool stop;

	std::atomic_ulong total_queued;
	std::atomic_ulong queued;
	std::atomic_ulong done;

55
    std::string title;
Damien Leroux's avatar
Damien Leroux committed
56
    std::mutex title_mutex;
Damien Leroux's avatar
Damien Leroux committed
57
58
    std::unordered_map<std::thread::id, std::vector<std::string>>* thread_stacks;
    std::thread::id master_id;
59

60
61
62
63
64
65
66
	void display_progress();
};

inline void ThreadPool::display_progress()
{
	if (!msg_handler_t::color()) {
		return;
67
68
69
70
71
    } else {
        static constexpr const char* const SAVE_CURSOR = "\033[s";
        static constexpr const char* const RESTORE_CURSOR = "\033[u";
        static constexpr const char* const ERASE_TO_EOL = "\033[K";
        static constexpr const char* const GOTO_0_0 = "\033[0;0H";
72
73
        /*static constexpr const char* const HIDE_CURSOR = "\033?25l";*/
        /*static constexpr const char* const SHOW_CURSOR = "\033?25h";*/
74

75
76
77
78
        /*std::unique_lock<msg_handler_t::lock_type> lock(msg_handler_t::mutex);*/
        if (msg_handler_t::instance().queue.m_stop) {
            return;
        }
79
80
        std::stringstream msg;
        msg << SAVE_CURSOR;
81
        msg /*<< HIDE_CURSOR*/ << GOTO_0_0;
82
        msg << msg_handler_t::i();
Damien Leroux's avatar
Damien Leroux committed
83
84
85
86
87
88
        msg << "[SPELL-QTL] Current: " << msg_handler_t::w();
        {
            std::lock_guard<std::mutex> lock(title_mutex);
            msg <<  title;
        }
        msg << msg_handler_t::i() << ERASE_TO_EOL << std::endl;
89
        msg << "[SPELL-QTL] " << msg_handler_t::n() << workers.size() << " threads, " << total_queued << " tasks queued in previous batches" << msg_handler_t::i() << ERASE_TO_EOL << std::endl;
90
        if (queued) {
91
92
93
94
95
            msg << "[SPELL-QTL] Task info: ";
            msg << msg_handler_t::n();
            msg << queued << " queued, " << done << " done, ";
            msg << msg_handler_t::w();
            msg << (100 * done / queued) << "% progress";
96
        }
97
        msg << ERASE_TO_EOL;
Damien Leroux's avatar
Damien Leroux committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
        msg << msg_handler_t::n() << std::endl;
        int ti = 0;
        std::stringstream master;
        std::stringstream workers;
        std::stringstream* tmp;
        for (const auto& kv: *thread_stacks) {
            std::thread::id id = kv.first;
            if (id == master_id) {
                master << "[MASTER] ";
                tmp = &master;
            } else {
                workers << '[' << (ti++) << "] ";
                tmp = &workers;
            }
            if (kv.second.size()) {
                (*tmp) << kv.second[0];
                for (size_t i = 1; i < kv.second.size(); ++i) {
                    (*tmp) << " | " << kv.second[i];
                }
            } else {
                (*tmp) << "<idle>";
            }
            (*tmp) << ERASE_TO_EOL << std::endl;
        }
        msg << master.str() << workers.str();
123
        msg << std::endl << "----------------------------------------------------------";
124
        msg << ERASE_TO_EOL << std::endl;
125
        msg << RESTORE_CURSOR /*<< SHOW_CURSOR*/;
126
127
128
129
        /*CREATE_MESSAGE(msg_channel::Out, msg.str());*/
        if (!msg_handler_t::instance().queue.m_stop) {
            msg_handler_t::instance().queue.cout << msg.str() << std::flush;
        }
130
131
132
133
134
135
        if (done == queued) {
            total_queued += queued;
            queued = 0;
            done = 0;
        }
    }
136
137
138
}
 
// the constructor just launches some amount of workers
Damien Leroux's avatar
Damien Leroux committed
139
140
141
inline ThreadPool::ThreadPool(size_t threads, std::unordered_map<std::thread::id, std::vector<std::string>>* tt)
    : stop(false), total_queued(0), queued(0), done(0), title(), thread_stacks(tt)
    , master_id(std::this_thread::get_id())
142
{
Damien Leroux's avatar
Damien Leroux committed
143
    for(size_t i = 0;i<threads;++i) {
144
145
146
147
148
        workers.emplace_back(
            [this]
            {
                while(true)
                {
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
                    {
                        std::unique_lock<std::mutex> lock(this->queue_mutex);
                        while(!this->stop && this->tasks.empty()) {
                            this->condition.wait(lock);
                        }
                        if(this->stop && this->tasks.empty()) {
                            return;
                        }
                        std::function<void()> task(this->tasks.front());
                        this->tasks.pop();
                        lock.unlock();
                        task();
                        ++done;
                    }
                    if (msg_handler_t::color()) {
164
                        msg_handler_t::instance().queue.lock_stream();
165
    					display_progress();
166
                        msg_handler_t::instance().queue.unlock_stream();
167
                    }
168
169
170
                }
            }
        );
Damien Leroux's avatar
Damien Leroux committed
171
172
173
174
        /*MSG_DEBUG("NEW THREAD [" << workers.back().get_id() << ']');*/
        thread_stacks->insert({workers.back().get_id(), {}});
    }
    thread_stacks->insert({master_id, {}});
175
    msg_handler_t::hook([this] () { display_progress(); });
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
}

// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) 
    -> std::future<typename std::result_of<F(Args...)>::type>
{
    typedef typename std::result_of<F(Args...)>::type return_type;
    
    // don't allow enqueueing after stopping the pool
    if(stop)
        throw std::runtime_error("enqueue on stopped ThreadPool");

    auto task = std::make_shared< std::packaged_task<return_type()> >(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );
        
    std::future<return_type> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        tasks.push([task](){ (*task)(); });
    }
	++queued;
    condition.notify_one();
    return res;
}

// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        stop = true;
    }
    condition.notify_all();
    for(size_t i = 0;i<workers.size();++i)
        workers[i].join();
}

#endif