-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_thread_pool.cpp
More file actions
61 lines (49 loc) · 1.44 KB
/
Copy path02_thread_pool.cpp
File metadata and controls
61 lines (49 loc) · 1.44 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <cassert>
#include <iostream>
#include <vector>
#include <vix/async/core/io_context.hpp>
#include <vix/async/core/task.hpp>
#include <vix/async/core/thread_pool.hpp>
using vix::async::core::io_context;
using vix::async::core::task;
static int heavy_work(int n)
{
// Fake CPU work
int acc = 0;
for (int i = 0; i < 200000; ++i)
acc += (i * n) % 97;
return acc;
}
static task<void> app(io_context &ctx)
{
std::cout << "[async] thread_pool demo start\n";
// Submit several CPU jobs in sequence (simple demo).
// Later we can add when_all / gather for parallel awaits.
int a = co_await ctx.cpu_pool().submit([]
{ return heavy_work(1); });
int b = co_await ctx.cpu_pool().submit([]
{ return heavy_work(2); });
int c = co_await ctx.cpu_pool().submit([]
{ return heavy_work(3); });
std::cout << "[async] results: " << a << ", " << b << ", " << c << "\n";
assert(a != 0 || b != 0 || c != 0);
// Fire-and-forget job
const bool accepted = ctx.cpu_pool().post([]
{
// This runs on a worker thread
volatile int x = 0;
for (int i = 0; i < 100000; ++i)
x += i; });
assert(accepted);
std::cout << "[async] demo done\n";
ctx.stop();
co_return;
}
int main()
{
io_context ctx;
auto t = app(ctx);
ctx.post(t.handle());
ctx.run();
return 0;
}