12-threads.cpp
819 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* 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>();
asio::executor_work_guard work_guard(io_svc->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_svc, i);
io_svc->post([] { std::cout << "Hello\n"; });
std::cin.get();
io_svc->stop();
for (auto &i : threads)
i.join();
return 0;
}