File: worker_asio.cpp

package info (click to toggle)
sight 25.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 43,108 kB
  • sloc: cpp: 306,170; xml: 18,037; ansic: 9,960; python: 1,379; sh: 144; makefile: 33
file content (376 lines) | stat: -rw-r--r-- 10,130 bytes parent folder | download
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/************************************************************************
 *
 * Copyright (C) 2009-2024 IRCAD France
 * Copyright (C) 2012-2020 IHU Strasbourg
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "core/thread/timer.hpp"
#include "core/thread/worker.hpp"

#include <core/time_stamp.hpp>

#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/bind.hpp>

#include <thread>

namespace sight::core::thread
{

//------------------------------------------------------------------------------

std::size_t worker_thread(SPTR(boost::asio::io_service)_io_service)
{
    std::size_t res = _io_service->run();
    return res;
}

/**
 * @brief Private implementation of core::thread::worker using boost::asio.
 */
class worker_asio : public core::thread::worker
{
public:

    using ioservice_type = boost::asio::io_service;
    using work_type      = boost::asio::io_service::work;
    using work_ptr_type  = std::shared_ptr<work_type>;
    using thread_type    = std::thread;

    worker_asio();

    ~worker_asio() override;

    void stop() override;

    void post(task_t _handler) override;

    [[nodiscard]] thread_id_t get_thread_id() const override;

    void set_thread_name(const std::string& _thread_name) const override;

    SPTR(core::thread::timer) create_timer() override;

    void process_tasks() override;

    void process_tasks(period_t _maxtime) override;

protected:

    /// Copy constructor forbidden
    worker_asio(const worker_asio&);

    /// Copy operator forbidden
    worker_asio& operator=(const worker_asio&);

private:

    /// Class provides functionality to manipulate asynchronous tasks.
    SPTR(ioservice_type) m_io_service;

    /// Class to inform the io_service when it has work to do.
    work_ptr_type m_work;

    /// Thread created and managed by the worker.
    SPTR(thread_type) m_thread;

    /// To avoid race conditions when calling stop()
    std::recursive_mutex m_stop_mutex;
};

//------------------------------------------------------------------------------

/**
 * @brief Private Timer implementation using boost::asio.
 */
class timer_asio : public core::thread::timer
{
public:

    SIGHT_DECLARE_CLASS(timer_asio, core::thread::timer);
    SIGHT_ALLOW_SHARED_FROM_THIS();

    /**
     * @brief Constructs a TimerAsio from given io_service.
     */
    explicit timer_asio(boost::asio::io_service& _io_srv);

    ~timer_asio() override;

    /// Starts or restarts the timer.
    void start() override;

    /// Stops the timer and cancel all pending operations.
    void stop() override;

    /// Sets time duration.
    void set_duration(time_duration_t _duration) override;

    /// Returns if the timer mode is 'one shot'.
    bool is_one_shot() const override
    {
        core::mt::scoped_lock lock(m_mutex);
        return m_one_shot;
    }

    /// Sets timer mode.
    void set_one_shot(bool _one_shot) override
    {
        core::mt::scoped_lock lock(m_mutex);
        m_one_shot = _one_shot;
    }

    /// Returns true if the timer is currently running.
    bool is_running() const override
    {
        core::mt::scoped_lock lock(m_mutex);
        return m_running;
    }

protected:

    void cancel_no_lock();
    void rearm_no_lock(time_duration_t _duration);

    /// Copy constructor forbidden.
    timer_asio(const timer_asio&);

    /// Copy operator forbidden.
    timer_asio& operator=(const timer_asio&);

private:

    friend struct timer_callback;

    /// Timer object.
    boost::asio::deadline_timer m_timer;

    /// Time to wait until timer's expiration.
    time_duration_t m_duration;

    /// Timer's mode.
    bool m_one_shot {false};

    /// Timer's state.
    bool m_running {false};
};

//------------------------------------------------------------------------------

// ---------- WorkerAsio private implementation ----------

worker_asio::worker_asio() :
    m_io_service(std::make_shared<ioservice_type>()),
    m_work(std::make_shared<work_type>(*m_io_service))
{
    std::packaged_task<core::thread::worker::exit_return_type()> task([this](auto&& ...)
            {
                                                                      return worker_thread(m_io_service);
            });
    std::future<core::thread::worker::exit_return_type> future = task.get_future();

    m_thread = std::make_shared<thread_type>(std::move(task));

    m_future = std::move(future);
}

//------------------------------------------------------------------------------

worker_asio::~worker_asio()
{
    std::unique_lock<std::recursive_mutex> lock(m_stop_mutex);

    SIGHT_ASSERT(
        "Worker must be properly stopped. Try to call stop() from the caller thread before.",
        !m_thread->joinable()
    );
}

//------------------------------------------------------------------------------

void worker_asio::stop()
{
    // stop() is also called in the destructor, so we need to put a critical section here
    std::unique_lock<std::recursive_mutex> lock(m_stop_mutex);

    SIGHT_ASSERT("Thread is not joinable", m_thread->joinable());
    SIGHT_ASSERT(
        "Can not destroy a thread while running it. Try to call stop() from the caller thread before.",
        m_thread->get_id() != core::thread::get_current_thread_id()
    );

    m_work.reset();
    m_thread->join();
}

//------------------------------------------------------------------------------

SPTR(core::thread::timer) worker_asio::create_timer()
{
    return std::make_shared<timer_asio>(*m_io_service);
}

//------------------------------------------------------------------------------

void worker_asio::post(task_t _handler)
{
    m_io_service->post(_handler);
}

//------------------------------------------------------------------------------

thread_id_t worker_asio::get_thread_id() const
{
    return m_thread->get_id();
}

//------------------------------------------------------------------------------

void worker_asio::set_thread_name(const std::string& _thread_name) const
{
    core::thread::set_thread_name(_thread_name, m_thread->native_handle());
}

//------------------------------------------------------------------------------

void worker_asio::process_tasks()
{
    m_io_service->poll();
}

//------------------------------------------------------------------------------

void worker_asio::process_tasks(period_t _maxtime)
{
    core::time_stamp time_stamp;
    time_stamp.set_life_period(_maxtime);
    time_stamp.modified();
    while(time_stamp.period_expired())
    {
        m_io_service->poll_one();
    }
}

// ---------- Worker ----------
SPTR(worker) worker::make()
{
    return std::make_shared<worker_asio>();
}

// ---------- Timer private implementation ----------

timer_asio::timer_asio(boost::asio::io_service& _io_srv) :
    m_timer(_io_srv),
    m_duration(std::chrono::seconds(1))
{
}

timer_asio::~timer_asio()
= default;

//------------------------------------------------------------------------------

void timer_asio::set_duration(time_duration_t _duration)
{
    core::mt::scoped_lock lock(m_mutex);
    m_duration = _duration;
}

//------------------------------------------------------------------------------

void timer_asio::start()
{
    core::mt::scoped_lock lock(m_mutex);
    this->rearm_no_lock(m_duration);
    m_running = true;
}

//------------------------------------------------------------------------------

void timer_asio::stop()
{
    core::mt::scoped_lock lock(m_mutex);
    if(m_running)
    {
        m_running = false;
        this->cancel_no_lock();
    }
}

//------------------------------------------------------------------------------

struct timer_callback
{
    //------------------------------------------------------------------------------

    static void call(const boost::system::error_code& _error, timer_asio::sptr _timer)
    {
        if(!_error)
        {
            timer_asio::time_duration_t duration;
            bool one_shot = false;
            {
                core::mt::scoped_lock lock(_timer->m_mutex);
                one_shot = _timer->m_one_shot;
                duration = _timer->m_duration;
            }

            if(!one_shot)
            {
                {
                    core::mt::scoped_lock lock(_timer->m_mutex);
                    if(_timer->m_running)
                    {
                        _timer->rearm_no_lock(duration);
                    }
                }
                _timer->m_function();
            }
            else
            {
                _timer->m_function();
                core::mt::scoped_lock lock(_timer->m_mutex);
                _timer->m_running = false;
            }
        }
    }
};

//------------------------------------------------------------------------------

void timer_asio::rearm_no_lock(time_duration_t _duration)
{
    this->cancel_no_lock();
    boost::posix_time::time_duration d =
        boost::posix_time::microseconds(std::chrono::duration_cast<std::chrono::microseconds>(_duration).count());
    m_timer.expires_from_now(d);
    // NOLINTNEXTLINE(modernize-avoid-bind)
    m_timer.async_wait(boost::bind(timer_callback::call, boost::asio::placeholders::error, this->get_sptr()));
}

//------------------------------------------------------------------------------

void timer_asio::cancel_no_lock()
{
    m_timer.cancel();
}

} //namespace sight::core::thread