Project SkyFire Core
SkyFire 5.4.8 server core API documentation
Loading...
Searching...
No Matches
BoostAsioTaskRunner.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_TASK_RUNNER_H
7#define SF_BOOST_ASIO_TASK_RUNNER_H
8
11
12#include <functional>
13#include <utility>
14
15namespace Skyfire
16{
17namespace Asio
18{
20 {
21 public:
22 typedef std::function<void()> Task;
23
25 {
26 Join();
27 }
28
29 bool IsRunning() const { return _thread.IsRunning(); }
30
31 int Start(Task task)
32 {
33 if (!task || _thread.IsRunning())
34 return -1;
35
36 _executor.Restart();
37 _executor.KeepAlive();
38
39 if (_thread.Start(_executor) == -1)
40 {
41 _executor.ResetWork();
42 _executor.Restart();
43 return -1;
44 }
45
46 try
47 {
48 _executor.Post([this, task = std::move(task)]() mutable
49 {
50 struct WorkReset
51 {
52 explicit WorkReset(IoContextExecutor& executor) : Executor(executor) { }
53 ~WorkReset() { Executor.ResetWork(); }
54
55 IoContextExecutor& Executor;
56 } reset(_executor);
57
58 task();
59 });
60 }
61 catch (...)
62 {
63 _executor.ResetWork();
64 _executor.Stop();
65 _thread.Join();
66 _executor.Restart();
67 return -1;
68 }
69
70 return 0;
71 }
72
73 int Join()
74 {
75 _executor.ResetWork();
76 int const result = _thread.Join();
77 _executor.Restart();
78 return result;
79 }
80
81 private:
84 };
85}
86}
87
88#endif