Search code examples
c++webassemblyemscripten

Emscripten: Can't using emscripten::val in pthread


I'm working on project to attach video from c++.

I have success create video element from c++.

video = emscripten::val::global("document").call<emscripten::val>("createElement", emscripten::val("video"));
video.set("src", emscripten::val("http://jplayer.org/video/webm/Big_Buck_Bunny_Trailer.webm"));  
video.set("crossOrigin", emscripten::val("Anonymous"));
video.set("autoplay", emscripten::val(true));
video.call<void>("load");

But the problem came up is I have to wait until video buffer load enough to play.

My solution is using pthread to create thread wait until video buffer load enough and do stuff with the video.

 pthread_create(&threadVideo, NULL, attachVideo, NULL);

And inside attachVideo function

void *attachVideo(void *arg)
{
    pthread_detach(pthread_self());
    cout << "ready to run" << endl;
    cout << "readyState: " << video["readyState"].as<int>() << endl;
    pthread_exit(NULL);
}

And when I run it cameout error: Cannot read properties of undefined (reading 'value')"

Can someone help me with this ?


Solution

  • This is because emscripten::val is represents an object in JS and the JS state is all thread local. Another way of putting it: Each thread gets is own JS environment, so emscripten::val cannot be shared between threads.