Project SkyFire Core
SkyFire 5.4.8 server core API documentation
Loading...
Searching...
No Matches
BoostAsioThread.h
Go to the documentation of this file.
1/*
2* This file is part of Project SkyFire https://www.projectskyfire.org.
3* See LICENSE.md file for Copyright information
4*/
5
6#ifndef SF_BOOST_ASIO_THREAD_H
7#define SF_BOOST_ASIO_THREAD_H
8
10
11#include <atomic>
12#include <functional>
13#include <thread>
14#include <utility>
15
16namespace Skyfire
17{
18namespace Asio
19{
21 {
22 public:
23 typedef std::function<void()> Hook;
24
26
28 {
29 Join();
30 }
31
32 bool IsRunning() const { return _running; }
33
34 int Start(IoContextExecutor& executor, Hook preRun = Hook(), Hook postRun = Hook())
35 {
36 bool expected = false;
37 if (!_running.compare_exchange_strong(expected, true))
38 return -1;
39
40 _preRun = std::move(preRun);
41 _postRun = std::move(postRun);
42
43 try
44 {
45 _thread = std::thread(&IoContextThread::Run, this, &executor);
46 }
47 catch (...)
48 {
49 _preRun = Hook();
50 _postRun = Hook();
51 _running = false;
52 return -1;
53 }
54
55 return 0;
56 }
57
58 int Join()
59 {
60 if (_thread.joinable())
61 _thread.join();
62
63 _preRun = Hook();
64 _postRun = Hook();
65 _running = false;
66 return 0;
67 }
68
69 private:
70 void Run(IoContextExecutor* executor)
71 {
72 if (_preRun)
73 _preRun();
74
75 executor->Run();
76
77 if (_postRun)
78 _postRun();
79 }
80
81 std::thread _thread;
84 std::atomic<bool> _running;
85 };
86}
87}
88
89#endif
int Start(IoContextExecutor &executor, Hook preRun=Hook(), Hook postRun=Hook())
std::function< void()> Hook
void Run(IoContextExecutor *executor)