MCPcopy Create free account
hub / github.com/ThePhD/sol2 / main

Function main

examples/source/coroutine_multiple_stacks.cpp:7–51  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5#include <iostream>
6
7int main() {
8 std::cout << "=== coroutine - multple threads ==="
9 << std::endl;
10
11 sol::state lua;
12 lua.open_libraries(sol::lib::base,
13 sol::lib::package,
14 sol::lib::coroutine);
15
16 lua["print"] = [](sol::object v) {
17 std::cout << v.as<std::string>() << std::endl;
18 };
19 lua["cyield"] = sol::yielding(
20 []() { std::cout << "YIELDING" << std::endl; });
21
22 // notice the new threads!
23 sol::thread thread1 = sol::thread::create(lua);
24 sol::thread thread2 = sol::thread::create(lua);
25
26 // notice we load it FROM the new "execution stack"
27 // we need it to have thread1's stack perspective
28 sol::coroutine co1 = thread1.state().load(R"(
29 print("AA : Step 1")
30 cyield()
31 print("AA : Step 2")
32 )");
33 // call first coroutine here
34 co1();
35
36 // notice we load it FROM the new "execution stack"
37 // we need it to have thread2's stack and perspective
38 sol::coroutine co2 = thread2.state().load(R"(
39 print("BB : Step 1")
40 cyield()
41 print("BB : Step 2")
42 )");
43
44 // run the other coroutine
45 co2();
46 co1();
47 // tada! they run on
48 // independent stacks
49
50 return 0;
51}

Callers

nothing calls this directly

Calls 4

yieldingFunction · 0.85
open_librariesMethod · 0.80
loadMethod · 0.80
stateMethod · 0.45

Tested by

no test coverage detected