-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.cpp
More file actions
55 lines (49 loc) · 1.29 KB
/
main.cpp
File metadata and controls
55 lines (49 loc) · 1.29 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
#include <coroutine>
#include <iostream>
#include <stdexcept>
#include <thread>
using namespace std;
auto switch_to_new_thread(jthread& out)
{
struct awaitable
{
jthread* p_out;
bool await_ready() { return false; }
void await_suspend(coroutine_handle<> h)
{
jthread& out = *p_out;
if (out.joinable())
throw runtime_error("Output jthread parameter not empty");
out = jthread([h] { h.resume(); });
// Potential undefined behavior: accessing potentially destroyed *this
// cout << "New thread ID: " << p_out->get_id() << '\n';
cout << "New thread ID: " << out.get_id() << '\n'; // this is OK
}
void await_resume() {}
};
return awaitable{&out};
}
struct task
{
struct promise_type
{
task get_return_object() { return {}; }
suspend_never initial_suspend() { return {}; }
suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
task resuming_on_new_thread(jthread& out)
{
cout << "Coroutine started on thread: " << this_thread::get_id() << '\n';
co_await switch_to_new_thread(out);
// awaiter destroyed here
cout << "Coroutine resumed on thread: " << this_thread::get_id() << '\n';
}
int main()
{
jthread out;
resuming_on_new_thread(out);
return 0;
}