Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimal working example for emscripten webworker

I'm trying to build a basic webworker example in C++ with emscripten. The API looks very simple, but I can't get it working. I actually wanted to implement this functionality in my project, but after failing tried to make a minimal example and it also doesn't work.

I have main.cpp:

#include <emscripten/emscripten.h>
#include <emscripten/bind.h>
#include <iostream>

namespace e = emscripten;

int counter = 0;

void cback(char* data, int size, void* arg) {
    std::cout << "Callback" << std::endl;
    counter++;
}

void loop() {
    std::cout << "Counter: " << counter << std::endl;
}

int main() {
    std::cout << "Main func." << std::endl;
    worker_handle worker = emscripten_create_worker("worker.js");
    emscripten_call_worker(worker, "one", 0, 0, cback, (void*)42);

    emscripten_set_main_loop(loop, 2, true);

    return 0;
}

and worker.cpp:

#include <iostream>
#include <emscripten/emscripten.h>

extern "C" {

void one(char* data, int size) {
    for(int i=0; i<10; i++) {
        std::cout << "Worker" << std::endl;
        emscripten_worker_respond_provisionally(0, 0);
    }
    emscripten_worker_respond(0, 0);
}
}

compiled via

emcc -std=c++11 main.cpp -o main.js
emcc -std=c++11 worker.cpp -s EXPORTED_FUNCTIONS="['_one']" -o worker.js

and a simple js load via <script> tag on the html side.

Main loads and starts, outputs Main func. and then worker js is downloaded. But neither Worker nor Callback is outputed. No errors reported.

like image 745
Alexander Avatar asked Aug 29 '15 22:08

Alexander


1 Answers

Compile with BUILD_AS_WORKER flag.

emcc -std=c++11 worker.cpp -s EXPORTED_FUNCTIONS="['_one']" -s BUILD_AS_WORKER=1 -o worker.js
like image 180
zakki Avatar answered Nov 18 '22 23:11

zakki