xref: /wasmtime-44.0.1/examples/interrupt.cc (revision 13ebd6f5)
1 /*
2 Example of instantiating of the WebAssembly module and invoking its exported
3 function.
4 
5 You can compile and run this example on Linux with:
6 
7    cargo build --release -p wasmtime-c-api
8    c++ examples/interrupt.cc -std=c++20 \
9        -I crates/c-api/include \
10        -I crates/c-api/wasm-c-api/include \
11        target/release/libwasmtime.a \
12        -lpthread -ldl -lm \
13        -o interrupt
14    ./interrupt
15 
16 Note that on Windows and macOS the command will be similar, but you'll need
17 to tweak the `-lpthread` and such annotations as well as the name of the
18 `libwasmtime.a` file on Windows.
19 */
20 
21 #include <chrono>
22 #include <fstream>
23 #include <iostream>
24 #include <sstream>
25 #include <thread>
26 #include <wasmtime.hh>
27 
28 using namespace wasmtime;
29 
readFile(const char * name)30 std::string readFile(const char *name) {
31   std::ifstream watFile;
32   watFile.open(name);
33   std::stringstream strStream;
34   strStream << watFile.rdbuf();
35   return strStream.str();
36 }
37 
main()38 int main() {
39   // Enable interruptible code via `Config` and then create an interrupt
40   // handle which we'll use later to interrupt running code.
41   Config config;
42   config.epoch_interruption(true);
43   Engine engine(std::move(config));
44   Store store(engine);
45   store.context().set_epoch_deadline(1);
46 
47   // Compile and instantiate a small example with an infinite loop.
48   auto wat = readFile("examples/interrupt.wat");
49   Module module = Module::compile(engine, wat).unwrap();
50   Instance instance = Instance::create(store, module, {}).unwrap();
51   Func run = std::get<Func>(*instance.get(store, "run"));
52 
53   // Spin up a thread to send us an interrupt in a second
54   std::thread t([engine{std::move(engine)}]() {
55     std::this_thread::sleep_for(std::chrono::seconds(1));
56     std::cout << "Interrupting!\n";
57     engine.increment_epoch();
58   });
59 
60   std::cout << "Entering infinite loop ...\n";
61   auto err = run.call(store, {}).err();
62   auto &trap = std::get<Trap>(err.data);
63 
64   std::cout << "trap: " << trap.message() << "\n";
65   t.join();
66 }
67