Commit ad581d42d2d1ebeb0601ea40b1fd73b946838f62

Authored by Grzegorz Jabłoński
1 parent a8ad056a

Updated mutithreaded example

Showing 1 changed file with 8 additions and 12 deletions
13-daytime8.cpp
... ... @@ -15,8 +15,6 @@
15 15  
16 16 using asio::ip::tcp;
17 17  
18   -std::shared_ptr<asio::io_context> io_context;
19   -
20 18 std::string make_daytime_string() {
21 19 using namespace std; // For time_t, time and ctime;
22 20 time_t now = time(0);
... ... @@ -38,20 +36,18 @@ public:
38 36 tcp::socket &socket() { return socket_; }
39 37  
40 38 void start() {
41   - io_context->post([self = shared_from_this()] {
42   - self->message_ = make_daytime_string();
43   - asio::async_write(self->socket_, asio::buffer(self->message_),
44   - std::bind(&tcp_connection::handle_write, self,
45   - std::placeholders::_1,
46   - std::placeholders::_2));
47   - });
  39 + message_ = make_daytime_string();
  40 + asio::async_write(socket_, asio::buffer(message_),
  41 + std::bind(&tcp_connection::handle_write, this,
  42 + std::placeholders::_1, std::placeholders::_2));
48 43 }
49 44  
50 45 private:
51 46 tcp_connection(asio::io_context &io_context) : socket_(io_context) {}
52 47  
53 48 void handle_write(const asio::error_code &error, size_t bytes_transferred) {
54   - std::cout << error.category().name() << " : " << error.value() << " : " << error.message() << std::endl;
  49 + std::cout << error.category().name() << " : " << error.value() << " : "
  50 + << error.message() << std::endl;
55 51 if (error)
56 52 std::cout << "Error" << std::endl;
57 53 else
... ... @@ -83,7 +79,7 @@ private:
83 79 void handle_accept(tcp_connection::pointer new_connection,
84 80 const asio::error_code &error) {
85 81 if (!error) {
86   - new_connection->start();
  82 + io_context_.post(std::bind(&tcp_connection::start, new_connection));
87 83 }
88 84  
89 85 start_accept();
... ... @@ -97,7 +93,7 @@ void WorkerThread(std::shared_ptr&lt;asio::io_context&gt; io_svc) { io_svc-&gt;run(); }
97 93  
98 94 int main() {
99 95 try {
100   - io_context = std::make_shared<asio::io_context>();
  96 + auto io_context = std::make_shared<asio::io_context>();
101 97  
102 98 auto worker = std::make_shared<asio::io_context::work>(*io_context);
103 99  
... ...