12-threads.cpp
894 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
39
40
41
42
/* 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(asio::io_context& io_context, int counter) {
std::cout << counter << "\n";
io_context.run();
std::cout << "End.\n";
}
int main(void) {
asio::io_context 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, std::ref(io_context), i);
for(int i=0;i<10; ++i)
{
io_context.post([] { sleep(2); std::cout << "Hello\n";});
std::cout << "Posted" << std::endl;
}
std::cin.get();
io_context.stop();
for (auto &i : threads)
i.join();
return 0;
}