Quick intro into WebAssembly and Emscripten
Run
yarn start
- Open:
http://localhost:8080/index.html
Setup Emscripten
Option 1: Download and install Emscripten
Option 2: Docker image
docker pull trzeci/emscripten
docker run --rm -v ${pwd}:/src trzeci/emscripten emcc <emcc options here>
${pwd}
works on Windows PowerShell$(pwd)
works on Linux
Demo
Clean compiled files:
yarn clean
Fibonacci
Compile WebAssembly
emcc -O3 -s EXPORTED_RUNTIME_METHODS=["cwrap"] --minify 0 wasm/fib.c -o wasm/fib.wasm.js
or
docker run --rm -v ${pwd}/wasm:/src trzeci/emscripten emcc -O3 -s EXPORTED_RUNTIME_METHODS=["cwrap"] --minify 0 fib.c -o fib.wasm.js
-O3
: Optimize aggressively-s EXPORTED_RUNTIME_METHODS=["cwrap"]
: leave the cwrap() function available in the JavaScript file--minify 0
: disable generated JS code minification for demofib.c
file to compile
Outputs:
Notable files:
- - JS implementation
- - C implementation
- - Import wasm/fib.wasm.js
- - Extract binding for wasm function
- - Worker that loads wasm/fib.wasm.js
- - Using the worker
LKH example
LKH is an effective implementation of the Lin-Kernighan heuristic for solving the traveling salesman problem.
LKH is CLI-based. Input/output is controlled via file system files, and it is run using main function. This adds some complexity to using it in Emscripten.
Setup (already done):
- Download LKH-3.0.7.tgz
- Extract dot
lkh/src
- : comment in line 3:
#undef HAVE_GETRUSAGE
- Add following flags to
LKH
command in :-o ../../lkh.js -s MODULARIZE=1 -s EXPORTED_RUNTIME_METHODS='["FS", "callMain"]'
-o ../../lkh.js
: output file-s MODULARIZE=1
: use modules instead of automatically running main function. Re-runningmain
function is problematic, so for each call we initiate module again-s EXPORTED_RUNTIME_METHODS='["FS", "callMain"]'
- FS - add file system support
- callMain - allow calling main function
Compile WebAssembly
emmake make
or
docker run --rm -v ${pwd}/lkh:/src trzeci/emscripten /bin/bash -c "cd src; emmake make"
Outputs:
Notable files:
Node
Run LKH with 50 nodes in synchronous mode and in worker thread.
yarn lkh