sirisian / ecmascript-types

ECMAScript Optional Static Typing Proposal http://sirisian.github.io/ecmascript-types/
453 stars 4 forks source link

Create a section explaining how all types should be shared by default to allow for simple threading #67

Open sirisian opened 2 years ago

sirisian commented 2 years ago

I've been thinking about this for a while that ECMAScript needs real threading where any function can be spawned as a thread to run asynchronously. Any data should be accessible if the user wants it to be. This is related to #66 but extends to all typed variables. The syntax and bloat should be non-existent for working with threads.

The big picture is you should be able to define a global a:uint32 and Atomics.add(a, 5) it without shuffling it into a typed array.

In the far bigger picture ECMAScript should have concurrent queue data structures later that allow intuitive moving of objects across threads. (Also other concurrent data structures).

let a:uint32 = 0; 
function A() {
    Atomics.add(a, 5);
}
async function B() {
    A();
    Atomics.add(a, 5);
}
// Naive call syntax to show these execute on their own thread and callThread returns a promise.
await Promise.all([A.callThread(), B.callThread()]); // Join
console.log(a); // 15

There's a lot of details like killing threads and such and how that could or might work, but it's not super important. The goal here is to show how powerful making everything shared by default and accessible in threads is.

The callThread above could be replaced with any special syntax. Like thread A() and would return a promise.

Undefined behavior would be allowed with code like:

let a:uint32 = 0;
function A() {
    while (true) {
        a++;
    }
}
thread A();
await new Promise(resolve => setTimeout(resolve, 100));
console.log(a);

Threading in general is an advanced topic, but a user that's doing a complex task should be able to create a simple thread to do the work and await the result. The idea is to make it just work without any boilerplate.

Current applications are rare, but sorting very large arrays and performing client-side computation can be thrown to another thread ensuring that the main thread isn't blocked.

Future applications:

TODO: How do pipelines fit into this? Intuitively piping data to a threaded function should just work and create a thread. Is that a realistic scenario though?

sirisian commented 1 year ago

https://github.com/sirisian/ecmascript-types/blob/master/threading.md