12-threads.cpp 847 Bytes
/* multithreads.cpp */
#include <asio/ts/io_context.hpp>
#include <asio/ts/net.hpp>
#include <asio/ts/socket.hpp>

#include <iostream>

int a = 0;

void WorkerThread(std::shared_ptr<asio::io_context> io_context, int counter) {
  std::cout << counter << ".\n";
  io_context->run();
  std::cout << "End.\n";
}

int main(void) {

  auto io_context = std::make_shared<asio::io_context>();

  asio::executor_work_guard work_guard(io_context->get_executor()); //prevent run() from exiting immediately after all work is done

  std::cout << "Press ENTER key to exit!" << std::endl;

  std::vector<std::thread> threads;
  for (int i = 0; i < 5; i++)
    threads.emplace_back(WorkerThread, io_context, i);

  io_context->post([] { std::cout << "Hello\n"; });

  std::cin.get();

  io_context->stop();

  for (auto &i : threads)
    i.join();

  return 0;
}