Commit 2242157f8f231827831a18fcf28fe043b48afc7c

Authored by Grzegorz Jabłoński
1 parent 4b29a8c9

Updated mutithreaded example

Showing 1 changed file with 8 additions and 8 deletions
12-threads.cpp
... ... @@ -7,32 +7,32 @@
7 7  
8 8 int a = 0;
9 9  
10   -void WorkerThread(std::shared_ptr<asio::io_context> io_context, int counter) {
  10 +void WorkerThread(asio::io_context& io_context, int counter) {
11 11 std::cout << counter << ".\n";
12   - io_context->run();
  12 + io_context.run();
13 13 std::cout << "End.\n";
14 14 }
15 15  
16 16 int main(void) {
17 17  
18   - auto io_context = std::make_shared<asio::io_context>();
  18 + asio::io_context io_context;
19 19  
20   - asio::executor_work_guard work_guard(io_context->get_executor()); //prevent run() from exiting immediately after all work is done
  20 + asio::executor_work_guard work_guard(io_context.get_executor()); //prevent run() from exiting immediately after all work is done
21 21  
22 22 std::cout << "Press ENTER key to exit!" << std::endl;
23 23  
24 24 std::vector<std::thread> threads;
25 25 for (int i = 0; i < 5; i++)
26   - threads.emplace_back(WorkerThread, io_context, i);
  26 + threads.emplace_back(WorkerThread, std::ref(io_context), i);
27 27  
28   - io_context->post([] { std::cout << "Hello\n"; });
  28 + io_context.post([] { std::cout << "Hello\n"; });
29 29  
30 30 std::cin.get();
31 31  
32   - io_context->stop();
  32 + io_context.stop();
33 33  
34 34 for (auto &i : threads)
35 35 i.join();
36 36  
37 37 return 0;
38   -}
39 38 \ No newline at end of file
  39 +}
... ...