| 77 | } |
| 78 | |
| 79 | int main(int argc, const char *argv[]) { |
| 80 | // Initialize. |
| 81 | std::cout << "Initializing..." << std::endl; |
| 82 | auto engine = wasm::Engine::make(); |
| 83 | |
| 84 | // Load binary. |
| 85 | std::cout << "Loading binary..." << std::endl; |
| 86 | std::ifstream file("threads.wasm"); |
| 87 | file.seekg(0, std::ios_base::end); |
| 88 | auto file_size = file.tellg(); |
| 89 | file.seekg(0); |
| 90 | auto binary = wasm::vec<byte_t>::make_uninitialized(file_size); |
| 91 | file.read(binary.get(), file_size); |
| 92 | file.close(); |
| 93 | if (file.fail()) { |
| 94 | std::cout << "> Error loading module!" << std::endl; |
| 95 | return 1; |
| 96 | } |
| 97 | |
| 98 | // Compile and share. |
| 99 | std::cout << "Compiling and sharing module..." << std::endl; |
| 100 | auto store = wasm::Store::make(engine.get()); |
| 101 | auto module = wasm::Module::make(store.get(), binary); |
| 102 | auto shared = module->share(); |
| 103 | |
| 104 | // Spawn threads. |
| 105 | std::cout << "Spawning threads..." << std::endl; |
| 106 | std::mutex mutex; |
| 107 | std::thread threads[N_THREADS]; |
| 108 | for (int i = 0; i < N_THREADS; ++i) { |
| 109 | { |
| 110 | std::lock_guard<std::mutex> lock(mutex); |
| 111 | std::cout << "Initializing thread " << i << "..." << std::endl; |
| 112 | } |
| 113 | threads[i] = std::thread(run, engine.get(), shared.get(), &mutex, i); |
| 114 | } |
| 115 | |
| 116 | for (int i = 0; i < N_THREADS; ++i) { |
| 117 | { |
| 118 | std::lock_guard<std::mutex> lock(mutex); |
| 119 | std::cout << "Waiting for thread " << i << "..." << std::endl; |
| 120 | } |
| 121 | threads[i].join(); |
| 122 | } |
| 123 | |
| 124 | return 0; |
| 125 | } |