MCPcopy Create free account
hub / github.com/bytecodealliance/wasmtime / run_worker

Function run_worker

examples/threads.cc:41–85  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

39std::mutex print_mutex;
40
41void run_worker(Engine engine, Module module) {
42 std::thread::id id = std::this_thread::get_id();
43 Store store(engine);
44 for (int i = 0; i < N_REPS; i++) {
45 {
46 std::lock_guard<std::mutex> lock(print_mutex);
47 std::cout << "Instantiating module...\n";
48 }
49 Func hello_func = Func::wrap(store, []() {
50 std::lock_guard<std::mutex> lock(print_mutex);
51 std::thread::id id = std::this_thread::get_id();
52 std::cout << "> Hello from ThreadId(" << id << ")\n";
53 });
54 auto instance_res = Instance::create(store, module, {hello_func});
55 if (!instance_res) {
56 std::cout << "> Error instantiating module!\n";
57 return;
58 }
59 Instance instance = instance_res.unwrap();
60 Func run = std::get<Func>(*instance.get(store, "run"));
61 {
62 std::lock_guard<std::mutex> lock(print_mutex);
63 std::cout << "Executing...\n";
64 }
65 run.call(store, {}).unwrap();
66 std::this_thread::sleep_for(std::chrono::milliseconds(100));
67 }
68
69 // Move store to a new thread once.
70 {
71 std::lock_guard<std::mutex> lock(print_mutex);
72 std::cout << "> Moving (" << id << ") to a new thread\n";
73 }
74 auto handle = std::thread([store = std::move(store), module]() mutable {
75 Func hello_func = Func::wrap(store, []() {
76 std::lock_guard<std::mutex> lock(print_mutex);
77 std::thread::id id = std::this_thread::get_id();
78 std::cout << "> Hello from ThreadId(" << id << ")\n";
79 });
80 Instance instance = Instance::create(store, module, {hello_func}).unwrap();
81 Func run = std::get<Func>(*instance.get(store, "run"));
82 run.call(store, {}).unwrap();
83 });
84 handle.join();
85}
86
87int main() {
88 std::cout << "Initializing...\n";

Callers

nothing calls this directly

Calls 5

createFunction · 0.50
unwrapMethod · 0.45
getMethod · 0.45
callMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected