Skip to content

Configure pthread count, toggle shared memory

Compare
Choose a tag to compare
@Birch-san Birch-san released this 08 Jan 20:47
· 111 commits to main since this release

added params pthreadCount and sharedMemEnabled to Box2DFactory.

you can pass factory args like this:

import Box2DFactory from 'box2d3-wasm';
const box2d = await Box2DFactory({
  pthreadCount: 0
});

pthreadCount

set pthreadCount: 0 if you're running in an environment that doesn't support web workers.

set pthreadCount: 4 if you're targeting a wide/unknown variety of devices.
The goal is not "use every thread the device has", the best performance is achieved by "keeping the work within a single CCD (group of CPU cores) so that all CPU cores can share 1 cache, and avoid syncing memory between clusters of threads".
threads tend to come in clusters of 4 or 8. if you don't know which device you're targeting: stick to 4.

the default pthreadCount is globalThis.navigator?.hardwareConcurrency ?? 4, which will use all your cores. this is probably not a good default.

on NodeJS 20, globalThis.navigator.hardwareConcurrency is not implemented. you can instead obtain "number of cores" via the os API:

require("os").cpus().length

sharedMemEnabled

shared memory is required for threading.
if you are using pthreadCount: 0,
you probably want sharedMemEnabled: false too.

this is untested functionality.

perhaps non-shared memory can be a little faster (there's no need to synchronize caches or worry about concurrent reads/writes).

the most important thing is that some older browsers do not support growing shared memory.
on such browsers, you may wish/need to turn off shared memory (and threading), in order to be able to grow your memory.