Using WebWorkers with Cheerp

Alessandro Pignotti edited this page Dec 14, 2015 · 2 revisions

This documentation is experimental and pre-release. Using WebWorkers with Cheerp should be stable though.

WebWorkers vs. PThreads

PThreads is the main threading API on posix platforms, such as Linux. It makes it possible to run concurrent threads of execution that have the same view of memory (i.e. they run in the same address space).

WebWorkers are a message based concurrency API for the Web platform. A WebWorker is a "thread" which executes a JavaScript file which is completely independent and isolated from the main page code and other WebWorkers. Since the script inside a WebWorker has an isolated view of memory a WebWorker is more similar to a native process, than to a native thread.

PThread in Cheerp?

Cheerp does not support PThread APIs, as they cannot be mapped on equivalent APIs for the Web platform.

WebWorkers in Cheerp!

Cheerp is designed to give you full access to all browser APIs, including WebWorkers.

Using WebWorkers with Cheerp

You can use Cheerp to generate JavaScript running in the Worker, JavaScript in the main page that run a Worker, or both. Below you find a trivial example ported from http://www.html5rocks.com/en/tutorials/workers/basics/.

// cheerpworkerhost.cpp: Code to include in the HTML page
#include <cheerp/client.h>
#include <cheerp/clientlib.h>

using namespace client;

void webMain()
{
        Worker* w = new Worker("cheerpworker.js");
        w->addEventListener("message", cheerp::Callback([](MessageEvent* e) {
                                        console.log((String*)(e->get_data())); }));
        w->postMessage("Hello World");
}
// cheerpworker.cpp: Code that run inside the worker
#include <cheerp/clientlib.h>
#include <cheerp/client.h>

using namespace client;

void webMain()
{
        addEventListener("message", cheerp::Callback([](MessageEvent* e) { postMessage(e->get_data()); }));
}

You can build each files using the following command line (for more information see Getting Started)

/opt/cheerp/bin/clang++ -target cheerp file.cpp -o file.js

For your convenience here is the needed HTML to execute the code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Cheerp test</title>
    <script src="cheerpworkerhost.js"></script>
  </head>
  <body>
  </body>
</html>
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.