Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Play around with sieves and benchmarking...

Views: 276
Image: ubuntu2004
1
/**
2
* @license
3
* Copyright 2015 The Emscripten Authors
4
* SPDX-License-Identifier: MIT
5
*/
6
7
// Pthread Web Worker startup routine:
8
// This is the entry point file that is loaded first by each Web Worker
9
// that executes pthreads on the Emscripten application.
10
11
'use strict';
12
13
var Module = {};
14
15
// Node.js support
16
if (typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string') {
17
// Create as web-worker-like an environment as we can.
18
19
var nodeWorkerThreads = require('worker_threads');
20
21
var parentPort = nodeWorkerThreads.parentPort;
22
23
parentPort.on('message', function(data) {
24
onmessage({ data: data });
25
});
26
27
var nodeFS = require('fs');
28
29
Object.assign(global, {
30
self: global,
31
require: require,
32
Module: Module,
33
location: {
34
href: __filename
35
},
36
Worker: nodeWorkerThreads.Worker,
37
importScripts: function(f) {
38
(0, eval)(nodeFS.readFileSync(f, 'utf8'));
39
},
40
postMessage: function(msg) {
41
parentPort.postMessage(msg);
42
},
43
performance: global.performance || {
44
now: function() {
45
return Date.now();
46
}
47
},
48
});
49
}
50
51
// Thread-local:
52
53
function assert(condition, text) {
54
if (!condition) abort('Assertion failed: ' + text);
55
}
56
57
function threadPrintErr() {
58
var text = Array.prototype.slice.call(arguments).join(' ');
59
console.error(text);
60
}
61
function threadAlert() {
62
var text = Array.prototype.slice.call(arguments).join(' ');
63
postMessage({cmd: 'alert', text: text, threadId: Module['_pthread_self']()});
64
}
65
// We don't need out() for now, but may need to add it if we want to use it
66
// here. Or, if this code all moves into the main JS, that problem will go
67
// away. (For now, adding it here increases code size for no benefit.)
68
var out = function() {
69
throw 'out() is not defined in worker.js.';
70
}
71
var err = threadPrintErr;
72
self.alert = threadAlert;
73
74
Module['instantiateWasm'] = function(info, receiveInstance) {
75
// Instantiate from the module posted from the main thread.
76
// We can just use sync instantiation in the worker.
77
var instance = new WebAssembly.Instance(Module['wasmModule'], info);
78
// TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193,
79
// the above line no longer optimizes out down to the following line.
80
// When the regression is fixed, we can remove this if/else.
81
receiveInstance(instance);
82
// We don't need the module anymore; new threads will be spawned from the main thread.
83
Module['wasmModule'] = null;
84
return instance.exports;
85
};
86
87
function moduleLoaded() {
88
}
89
90
self.onmessage = function(e) {
91
try {
92
if (e.data.cmd === 'load') { // Preload command that is called once per worker to parse and load the Emscripten code.
93
94
// Module and memory were sent from main thread
95
Module['wasmModule'] = e.data.wasmModule;
96
97
Module['wasmMemory'] = e.data.wasmMemory;
98
99
Module['buffer'] = Module['wasmMemory'].buffer;
100
101
Module['ENVIRONMENT_IS_PTHREAD'] = true;
102
103
if (typeof e.data.urlOrBlob === 'string') {
104
importScripts(e.data.urlOrBlob);
105
} else {
106
var objectUrl = URL.createObjectURL(e.data.urlOrBlob);
107
importScripts(objectUrl);
108
URL.revokeObjectURL(objectUrl);
109
}
110
111
// MINIMAL_RUNTIME always compiled Wasm (&Wasm2JS) asynchronously, even in pthreads. But
112
// regular runtime and asm.js are loaded synchronously, so in those cases
113
// we are now loaded, and can post back to main thread.
114
moduleLoaded();
115
116
} else if (e.data.cmd === 'objectTransfer') {
117
Module['PThread'].receiveObjectTransfer(e.data);
118
} else if (e.data.cmd === 'run') {
119
// This worker was idle, and now should start executing its pthread entry
120
// point.
121
// performance.now() is specced to return a wallclock time in msecs since
122
// that Web Worker/main thread launched. However for pthreads this can
123
// cause subtle problems in emscripten_get_now() as this essentially
124
// would measure time from pthread_create(), meaning that the clocks
125
// between each threads would be wildly out of sync. Therefore sync all
126
// pthreads to the clock on the main browser thread, so that different
127
// threads see a somewhat coherent clock across each of them
128
// (+/- 0.1msecs in testing).
129
Module['__performance_now_clock_drift'] = performance.now() - e.data.time;
130
131
// Pass the thread address inside the asm.js scope to store it for fast access that avoids the need for a FFI out.
132
Module['__emscripten_thread_init'](e.data.threadInfoStruct, /*isMainBrowserThread=*/0, /*isMainRuntimeThread=*/0);
133
134
// Establish the stack frame for this thread in global scope
135
// The stack grows downwards
136
var max = e.data.stackBase;
137
var top = e.data.stackBase + e.data.stackSize;
138
assert(e.data.threadInfoStruct);
139
assert(top != 0);
140
assert(max != 0);
141
assert(top > max);
142
// Also call inside JS module to set up the stack frame for this pthread in JS module scope
143
Module['establishStackSpace'](top, max);
144
Module['PThread'].receiveObjectTransfer(e.data);
145
Module['PThread'].threadInit();
146
147
try {
148
// pthread entry points are always of signature 'void *ThreadMain(void *arg)'
149
// Native codebases sometimes spawn threads with other thread entry point signatures,
150
// such as void ThreadMain(void *arg), void *ThreadMain(), or void ThreadMain().
151
// That is not acceptable per C/C++ specification, but x86 compiler ABI extensions
152
// enable that to work. If you find the following line to crash, either change the signature
153
// to "proper" void *ThreadMain(void *arg) form, or try linking with the Emscripten linker
154
// flag -s EMULATE_FUNCTION_POINTER_CASTS=1 to add in emulation for this x86 ABI extension.
155
var result = Module['invokeEntryPoint'](e.data.start_routine, e.data.arg);
156
157
Module['checkStackCookie']();
158
if (Module['keepRuntimeAlive']()) {
159
Module['PThread'].setExitStatus(result);
160
} else {
161
Module['PThread'].threadExit(result);
162
}
163
} catch(ex) {
164
if (ex === 'Canceled!') {
165
Module['PThread'].threadCancel();
166
} else if (ex != 'unwind') {
167
// FIXME(sbc): Figure out if this is still needed or useful. Its not
168
// clear to me how this check could ever fail. In order to get into
169
// this try/catch block at all we have already called bunch of
170
// functions on `Module`.. why is this one special?
171
if (typeof(Module['_emscripten_futex_wake']) !== "function") {
172
err("Thread Initialisation failed.");
173
throw ex;
174
}
175
// ExitStatus not present in MINIMAL_RUNTIME
176
if (ex instanceof Module['ExitStatus']) {
177
if (Module['keepRuntimeAlive']()) {
178
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' called exit(), staying alive due to noExitRuntime.');
179
} else {
180
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' called exit(), calling threadExit.');
181
Module['PThread'].threadExit(ex.status);
182
}
183
}
184
else
185
{
186
Module['PThread'].threadExit(-2);
187
throw ex;
188
}
189
} else {
190
// else e == 'unwind', and we should fall through here and keep the pthread alive for asynchronous events.
191
err('Pthread 0x' + Module['_pthread_self']().toString(16) + ' completed its pthread main entry point with an unwind, keeping the pthread worker alive for asynchronous operation.');
192
}
193
}
194
} else if (e.data.cmd === 'cancel') { // Main thread is asking for a pthread_cancel() on this thread.
195
if (Module['_pthread_self']()) {
196
Module['PThread'].threadCancel();
197
}
198
} else if (e.data.target === 'setimmediate') {
199
// no-op
200
} else if (e.data.cmd === 'processThreadQueue') {
201
if (Module['_pthread_self']()) { // If this thread is actually running?
202
Module['_emscripten_current_thread_process_queued_calls']();
203
}
204
} else {
205
err('worker.js received unknown command ' + e.data.cmd);
206
err(e.data);
207
}
208
} catch(ex) {
209
err('worker.js onmessage() captured an uncaught exception: ' + ex);
210
if (ex && ex.stack) err(ex.stack);
211
throw ex;
212
}
213
};
214
215
216
217