Commit 4b29a8c964cc73c23ecd9261d5c80d2b465641af

Authored by Grzegorz Jabłoński
1 parent 41ce4ed5

Updated mutithreaded example

Showing 1 changed file with 6 additions and 8 deletions
13-daytime8.cpp
... ... @@ -19,7 +19,7 @@ std::string make_daytime_string() {
19 19 using namespace std; // For time_t, time and ctime;
20 20 time_t now = time(0);
21 21  
22   - sleep(10);
  22 + sleep(5);
23 23  
24 24 char buf[26];
25 25 return ctime_r(&now, buf);
... ... @@ -89,26 +89,24 @@ private:
89 89 tcp::acceptor acceptor_;
90 90 };
91 91  
92   -void WorkerThread(std::shared_ptr<asio::io_context> io_svc) { io_svc->run(); }
93   -
94 92 int main() {
95 93 try {
96   - auto io_context = std::make_shared<asio::io_context>();
  94 + asio::io_context io_context;
97 95  
98   - asio::executor_work_guard work_guard(io_context->get_executor()); //prevent run() from exiting immediately after all work is done
  96 + asio::executor_work_guard work_guard(io_context.get_executor()); //prevent run() from exiting immediately after all work is done
99 97  
100 98 std::vector<std::thread> threads;
101 99  
102 100 for (int i = 0; i < 5; i++)
103   - threads.emplace_back(WorkerThread, io_context);
  101 + threads.emplace_back([&io_context]{io_context.run();});
104 102  
105   - tcp_server server(*io_context);
  103 + tcp_server server(io_context);
106 104  
107 105 std::cout << "Press ENTER key to exit!" << std::endl;
108 106  
109 107 std::cin.get();
110 108  
111   - io_context->stop();
  109 + io_context.stop();
112 110  
113 111 for (auto &i : threads)
114 112 i.join();
... ...