12-threads.cpp 758 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_svc, int counter) {
  std::cout << counter << ".\n";
  io_svc->run();
  std::cout << "End.\n";
}

int main(void) {

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

  auto worker = std::make_shared<asio::io_context::work>(*io_svc);

  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_svc, i);

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

  std::cin.get();

  io_svc->stop();

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

  return 0;
}