-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathNetworkResource.cpp
More file actions
84 lines (62 loc) · 1.81 KB
/
NetworkResource.cpp
File metadata and controls
84 lines (62 loc) · 1.81 KB
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <SFNUL/NetworkResource.hpp>
#include <SFNUL/ConfigInternal.hpp>
#include <SFNUL/MakeUnique.hpp>
#include <asio/io_context.hpp>
#include <asio/strand.hpp>
#include <deque>
namespace {
std::deque<std::shared_ptr<sfn::Thread>> asio_threads;
std::shared_ptr<asio::io_context::work> asio_work;
std::weak_ptr<asio::io_context> shared_io_context;
}
namespace sfn {
class NetworkResource::NetworkResourceImpl {
public:
NetworkResourceImpl() :
io_context{ shared_io_context.expired() ? std::make_shared<asio::io_context>() : shared_io_context.lock() },
strand{ *io_context }
{
if( shared_io_context.expired() ) {
shared_io_context = io_context;
}
}
std::shared_ptr<asio::io_context> io_context;
mutable asio::io_context::strand strand;
};
NetworkResource::NetworkResource() :
m_impl{ make_unique<NetworkResourceImpl>() }
{
}
NetworkResource::~NetworkResource() {
}
void* NetworkResource::GetIOService() const {
return m_impl->io_context.get();
}
void* NetworkResource::GetStrand() const {
return &m_impl->strand;
}
void Start( std::size_t threads ) {
auto io_context = shared_io_context.lock();
if( !io_context ) {
io_context = std::make_shared<asio::io_context>();
shared_io_context = io_context;
}
asio_work = std::make_shared<asio::io_context::work>( *io_context );
for( std::size_t index = 0; index < threads; index++ ) {
asio_threads.emplace_back( std::make_shared<Thread>( [=]() { io_context->run(); } ) );
}
}
void Stop() {
auto io_context = shared_io_context.lock();
if( !io_context ) {
return;
}
asio_work.reset();
io_context->stop();
asio_threads.clear();
io_context->reset();
}
}