Project SkyFire Core
SkyFire 5.4.8 server core API documentation
Loading...
Searching...
No Matches
BoostAsioThreadGroup.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_GROUP_H
7#define SF_BOOST_ASIO_THREAD_GROUP_H
8
10
11#include <atomic>
12#include <cstddef>
13#include <functional>
14#include <memory>
15#include <utility>
16#include <vector>
17
18namespace Skyfire
19{
20namespace Asio
21{
23 {
24 public:
25 typedef std::function<void()> Hook;
26
28
33
35 boost::asio::io_context& GetIoContext() { return _executor.GetIoContext(); }
36 bool IsRunning() const { return _running; }
37
38 int Start(std::size_t threadCount, Hook preRun = Hook(), Hook postRun = Hook())
39 {
40 if (threadCount == 0)
41 return -1;
42
43 bool expected = false;
44 if (!_running.compare_exchange_strong(expected, true))
45 return -1;
46
47 _executor.Restart();
48 _executor.KeepAlive();
49 _preRun = std::move(preRun);
50 _postRun = std::move(postRun);
51
52 try
53 {
54 for (std::size_t i = 0; i < threadCount; ++i)
55 {
56 std::unique_ptr<IoContextThread> thread(new IoContextThread);
57 if (thread->Start(_executor, _preRun, _postRun) == -1)
58 {
60 return -1;
61 }
62
63 _threads.push_back(std::move(thread));
64 }
65 }
66 catch (...)
67 {
69 return -1;
70 }
71
72 return 0;
73 }
74
75 void Drain()
76 {
77 _executor.ResetWork();
78 }
79
80 void Stop()
81 {
82 _executor.Stop();
83 _executor.ResetWork();
84 }
85
86 void Join()
87 {
88 for (std::unique_ptr<IoContextThread>& thread : _threads)
89 thread->Join();
90
91 _threads.clear();
92 _preRun = Hook();
93 _postRun = Hook();
94 _running = false;
95 }
96
98 {
99 Drain();
100 Join();
101 }
102
104 {
105 Stop();
106 Join();
107 }
108
109 private:
111 std::vector<std::unique_ptr<IoContextThread> > _threads;
114 std::atomic<bool> _running;
115 };
116}
117}
118
119#endif
std::vector< std::unique_ptr< IoContextThread > > _threads
int Start(std::size_t threadCount, Hook preRun=Hook(), Hook postRun=Hook())
boost::asio::io_context & GetIoContext()