diff options
Diffstat (limited to 'node_modules/webworker-threads/examples')
26 files changed, 989 insertions, 0 deletions
diff --git a/node_modules/webworker-threads/examples/demo.js b/node_modules/webworker-threads/examples/demo.js new file mode 100644 index 0000000..63316ae --- /dev/null +++ b/node_modules/webworker-threads/examples/demo.js @@ -0,0 +1,31 @@ +var http= require('http'); + +function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +function fast (req,res) { + process.stdout.write('·'); + res.end("FAST"); +} + +function slow (req,res) { + process.stdout.write('•'); + res.end("SLOW -> "+ fibo(40)); +} + +var numThreads= parseInt(process.argv[2], 10) || 5; +console.log("Using "+ numThreads+ " threads."); +var Worker= require('webworker-threads'); +var threadPool= Worker.createPool(numThreads).all.eval(fibo); + +function tagg (req,res) { + threadPool.any.eval('fibo(40)', function (err, data) { + process.stdout.write('❚'); + res.end("TAGG -> "+ data); //Threads A GoGo + }); +} + +http.createServer(fast).listen(12345), console.log("fast @ localhost:12345"); +http.createServer(slow).listen(12346), console.log("slow @ localhost:12346"); +http.createServer(tagg).listen(12347), console.log("useThreads @ localhost:12347"); diff --git a/node_modules/webworker-threads/examples/ex01_basic.js b/node_modules/webworker-threads/examples/ex01_basic.js new file mode 100644 index 0000000..e82cd9d --- /dev/null +++ b/node_modules/webworker-threads/examples/ex01_basic.js @@ -0,0 +1,63 @@ +/// !example +/// ## Running a simple function in a thread +/// +/// This first example demonstrates how you can run an expensive computation in +/// a worker thread and obtain its result. +/// +/// First, we define the function that we want to execute in the worker thread: +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} +/// Then, we create a worker thread with the `Threads.create` call: +var Threads = require('webworker-threads'); +var t = Threads.create(); +/// In the next step, we load the function into the worker thead. +/// We get the function's source with `fibo.toString()` and we +/// call `t.eval(source)` to evalutate it into the worker thread's context: +t.eval(fibo); +/// Now, we are ready to call this function. +/// We use the `t.eval` function again, with two arguments this time. +/// The first argument is the expression to evaluate. +/// The second one is a callback that receives the result (or an error if there was one). +t.eval('fibo(10)', function(err, result) { + if (err) throw err; // something abnormal + // print the result + console.log('fibo(10)=' + result); + // chain with next step + step2(); +}); +/// Let's call it again: +function step2() { + t.eval('fibo(20)', function(err, result) { + if (err) throw err; + console.log('fibo(20)=' + result); + step3(); + }); +} +/// If the expression is invalid, we get an error through the callback +function step3() { + // 'x' is not defined + t.eval('fibo(x)', function(err, result) { + console.log('error=' + err); + step4(); + }); +} +/// But the thread is still alive and ready to accept more calls: +function step4() { + t.eval('fibo(15)', function(err, result) { + console.log('fibo(15)=' + result); + step5(); + }); +} +/// Once we are done, we destroy the thread: +function step5() { + t.destroy(); +} +/// ### Output +/// +/// ``` +/// fibo(10)=89 +/// fibo(20)=10946 +/// error=Error: ReferenceError: x is not defined +/// fibo(15)=987 +/// ```
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex01_basic.md b/node_modules/webworker-threads/examples/ex01_basic.md new file mode 100644 index 0000000..21ee60d --- /dev/null +++ b/node_modules/webworker-threads/examples/ex01_basic.md @@ -0,0 +1,94 @@ +## Running a simple function in a thread + +This first example demonstrates how you can run an expensive computation in +a worker thread and obtain its result. + +First, we define the function that we want to execute in the worker thread: + +``` javascript +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} +``` + +Then, we create a worker thread with the `Threads.create` call: + +``` javascript +var Threads = require('webworker-threads'); +var t = Threads.create(); +``` + +In the next step, we load the function into the worker thead. +We get the function's source with `fibo.toString()` and we +call `t.eval(source)` to evalutate it into the worker thread's context: + +``` javascript +t.eval(fibo); +``` + +Now, we are ready to call this function. +We use the `t.eval` function again, with two arguments this time. +The first argument is the expression to evaluate. +The second one is a callback that receives the result (or an error if there was one). + +``` javascript +t.eval('fibo(10)', function(err, result) { + if (err) throw err; // something abnormal + // print the result + console.log('fibo(10)=' + result); + // chain with next step + step2(); +}); +``` + +Let's call it again: + +``` javascript +function step2() { + t.eval('fibo(20)', function(err, result) { + if (err) throw err; + console.log('fibo(20)=' + result); + step3(); + }); +} +``` + +If the expression is invalid, we get an error through the callback + +``` javascript +function step3() { + // 'x' is not defined + t.eval('fibo(x)', function(err, result) { + console.log('error=' + err); + step4(); + }); +} +``` + +But the thread is still alive and ready to accept more calls: + +``` javascript +function step4() { + t.eval('fibo(15)', function(err, result) { + console.log('fibo(15)=' + result); + step5(); + }); +} +``` + +Once we are done, we destroy the thread: + +``` javascript +function step5() { + t.destroy(); +} +``` + +### Output + +``` +fibo(10)=89 +fibo(20)=10946 +error=Error: ReferenceError: x is not defined +fibo(15)=987 +``` diff --git a/node_modules/webworker-threads/examples/ex02_events.js b/node_modules/webworker-threads/examples/ex02_events.js new file mode 100644 index 0000000..6d6bfac --- /dev/null +++ b/node_modules/webworker-threads/examples/ex02_events.js @@ -0,0 +1,54 @@ +/// !example +/// ## Sending events from a worker thread +/// +/// This second example demonstrates how we can use events to communicate from the worker +/// thread to the main thread. +/// +/// Like before, we create a thread and we define the fibonacci function: +var Threads = require('webworker-threads'); +var t = Threads.create(); + +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} +/// Instead of running a single fibonacci computation in the worker thread, we are going to execute a function +/// that computes all fibonacci numbers and emits a `data` event for every number it generates. +/// +/// This function runs inside the worker thread so it does not see the `t` variable which belongs to the +/// main thread. But **webworker-threads** sets up a global `thread` variable that the worker thread can use to +/// send events to the main thread. +/// +/// Here is our fibonacci generator: +function generateFibos(max) { + for (var i = 1; i <= max; i++) { + thread.emit("data", i, fibo(i)); + } +} +/// Note: this is obviously a very inefficient algorithm to generate the sequence of fibonacci numbers. +/// +/// Inside the main thread, we set up an event listener for the `data` events emitted by the +/// worker thread: +t.on('data', function(n, result) { + console.log('fibo(' + n + ') = ' + result); +}) +/// Now, we are ready to go. We load the two functions into the worker thread +t.eval(fibo); +t.eval(generateFibos); +/// And we run the generator with a callback that will execute when the generator returns from its loop: +t.eval("generateFibos(40)", function(err, result) { + if (err) throw err; + console.log("generator is done!"); + t.destroy(); +}); +/// ### Output +/// +/// ``` +/// fibo(1) = 1 +/// fibo(2) = 2 +/// fibo(3) = 3 +/// fibo(4) = 5 +/// ... +/// fibo(39) = 102334155 +/// fibo(40) = 165580141 +/// generator is done! +/// ```
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex02_events.md b/node_modules/webworker-threads/examples/ex02_events.md new file mode 100644 index 0000000..7819b17 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex02_events.md @@ -0,0 +1,73 @@ +## Sending events from a worker thread + +This second example demonstrates how we can use events to communicate from the worker +thread to the main thread. + +Like before, we create a thread and we define the fibonacci function: + +``` javascript +var Threads = require('webworker-threads'); +var t = Threads.create(); + +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} +``` + +Instead of running a single fibonacci computation in the worker thread, we are going to execute a function +that computes all fibonacci numbers and emits a `data` event for every number it generates. + +This function runs inside the worker thread so it does not see the `t` variable which belongs to the +main thread. But **webworker-threads** sets up a global `thread` variable that the worker thread can use to +send events to the main thread. + +Here is our fibonacci generator: + +``` javascript +function generateFibos(max) { + for (var i = 1; i <= max; i++) { + thread.emit("data", i, fibo(i)); + } +} +``` + +Note: this is obviously a very inefficient algorithm to generate the sequence of fibonacci numbers. + +Inside the main thread, we set up an event listener for the `data` events emitted by the +worker thread: + +``` javascript +t.on('data', function(n, result) { + console.log('fibo(' + n + ') = ' + result); +}) +``` + +Now, we are ready to go. We load the two functions into the worker thread + +``` javascript +t.eval(fibo); +t.eval(generateFibos); +``` + +And we run the generator with a callback that will execute when the generator returns from its loop: + +``` javascript +t.eval("generateFibos(40)", function(err, result) { + if (err) throw err; + console.log("generator is done!"); + t.destroy(); +}); +``` + +### Output + +``` +fibo(1) = 1 +fibo(2) = 2 +fibo(3) = 3 +fibo(4) = 5 +... +fibo(39) = 102334155 +fibo(40) = 165580141 +generator is done! +``` diff --git a/node_modules/webworker-threads/examples/ex03_ping_pong.js b/node_modules/webworker-threads/examples/ex03_ping_pong.js new file mode 100644 index 0000000..f2d7df4 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex03_ping_pong.js @@ -0,0 +1,57 @@ +/// !example +/// ## Sending events both ways between the main thread and a worker thread +/// +/// This third example demonstrates how we can use events to communicate in both directions +/// between main thread and worker thread. +/// +/// Like before, we create a worker thread and we define the fibonacci function: +var Threads = require('webworker-threads'); +var t = Threads.create(); + +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} +/// In the previous example we were running a loop that generates fibonacci numbers in the worker thread. +/// This is fine if the generator produces the number at a slower rate than the main thread can consume them +/// but it will hog memory if the main thread is too busy and cannot consume the data events fast enough. +/// We can improve this by controlling the flow with events in both directions. +/// +/// The `thread` global variable that **webworker-threads** predefines in every worker thread is also an `EventEmitter`. +/// So we will use it to send events in the other direction, from the main thread to the worker thread. +/// +/// Our modified generator does not use a loop any more. Instead, it generates numbers in response to `next` events +/// sent from the main thread. Here is the new generator: +function generateFibos() { + var i = 1; + thread.on('next', function() { + thread.emit('data', i, fibo(i)); + i++; + }); +} +/// From the main thread, we listen for the `data` events emitted by the worker thread. +/// Every time we get a `data` event from the worker thread, we print the result and we `emit` a +/// `next` event into the worker thread (stopping at 40): +t.on('data', function(n, result) { + console.log('fibo(' + n + ') = ' + result); + if (n < 40) t.emit('next'); + else console.log('bye!'), t.destroy(); +}); +/// We now have all we need for our little ping-pong game. We load the two functions into the thread: +t.eval(fibo); +t.eval(generateFibos); +/// We start the generator in the worker thread: +t.eval("generateFibos()"); +/// And we start the game by emitting the first `next` event: +t.emit('next'); +/// ### Output +/// +/// ``` +/// fibo(1) = 1 +/// fibo(2) = 2 +/// fibo(3) = 3 +/// fibo(4) = 5 +/// ... +/// fibo(39) = 102334155 +/// fibo(40) = 165580141 +/// bye! +/// ```
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex03_ping_pong.md b/node_modules/webworker-threads/examples/ex03_ping_pong.md new file mode 100644 index 0000000..826df60 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex03_ping_pong.md @@ -0,0 +1,80 @@ +## Sending events both ways between the main thread and a worker thread + +This third example demonstrates how we can use events to communicate in both directions +between main thread and worker thread. + +Like before, we create a worker thread and we define the fibonacci function: + +``` javascript +var Threads = require('webworker-threads'); +var t = Threads.create(); + +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} +``` + +In the previous example we were running a loop that generates fibonacci numbers in the worker thread. +This is fine if the generator produces the number at a slower rate than the main thread can consume them +but it will hog memory if the main thread is too busy and cannot consume the data events fast enough. +We can improve this by controlling the flow with events in both directions. + +The `thread` global variable that **webworker-threads** predefines in every worker thread is also an `EventEmitter`. +So we will use it to send events in the other direction, from the main thread to the worker thread. + +Our modified generator does not use a loop any more. Instead, it generates numbers in response to `next` events +sent from the main thread. Here is the new generator: + +``` javascript +function generateFibos() { + var i = 1; + thread.on('next', function() { + thread.emit('data', i, fibo(i)); + i++; + }); +} +``` + +From the main thread, we listen for the `data` events emitted by the worker thread. +Every time we get a `data` event from the worker thread, we print the result and we `emit` a +`next` event into the worker thread (stopping at 40): + +``` javascript +t.on('data', function(n, result) { + console.log('fibo(' + n + ') = ' + result); + if (n < 40) t.emit('next'); + else console.log('bye!'), t.destroy(); +}); +``` + +We now have all we need for our little ping-pong game. We load the two functions into the thread: + +``` javascript +t.eval(fibo); +t.eval(generateFibos); +``` + +We start the generator in the worker thread: + +``` javascript +t.eval("generateFibos()"); +``` + +And we start the game by emitting the first `next` event: + +``` javascript +t.emit('next'); +``` + +### Output + +``` +fibo(1) = 1 +fibo(2) = 2 +fibo(3) = 3 +fibo(4) = 5 +... +fibo(39) = 102334155 +fibo(40) = 165580141 +bye! +``` diff --git a/node_modules/webworker-threads/examples/ex04_main.js b/node_modules/webworker-threads/examples/ex04_main.js new file mode 100644 index 0000000..be8ca7c --- /dev/null +++ b/node_modules/webworker-threads/examples/ex04_main.js @@ -0,0 +1,40 @@ +/// !example +/// ## Loading the worker code from a file (main side) +/// +/// When writing code for threads we have both code that executes in the main thread and code that +/// executes in worker threads. When the code is small, it may be handy to have all code in a single file +/// but it is often clearer to split the code apart when the worker code starts to grow. +/// +/// This example demonstrates how we can package the worker code in a separeate file and +/// load it with `t.load`. +/// +/// We are going to keep the same logic as in our previous 'ping pong' example, but just repackage +/// it slightly differently. +/// +/// In this file we keep only the ping (main) side: +// Creating the worker thread +var Threads = require('webworker-threads'); +var t = Threads.create(); + +// Listening to 'data' events from the worker thread +t.on('data', function(n, result) { + console.log('fibo(' + n + ') = ' + result); + if (n < 40) t.emit('next'); + else console.log('bye!'), t.destroy(); +}); +/// At this point we load the worker code: +t.load(__dirname + '/ex04_worker.js'); +/// And we start the game by emitting the first `next` event: +t.emit('next'); +/// ### Output +/// +/// ``` +/// fibo(1) = 1 +/// fibo(2) = 2 +/// fibo(3) = 3 +/// fibo(4) = 5 +/// ... +/// fibo(39) = 102334155 +/// fibo(40) = 165580141 +/// bye! +/// ```
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex04_main.md b/node_modules/webworker-threads/examples/ex04_main.md new file mode 100644 index 0000000..f341518 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex04_main.md @@ -0,0 +1,51 @@ +## Loading the worker code from a file (main side) + +When writing code for threads we have both code that executes in the main thread and code that +executes in worker threads. When the code is small, it may be handy to have all code in a single file +but it is often clearer to split the code apart when the worker code starts to grow. + +This example demonstrates how we can package the worker code in a separeate file and +load it with `t.load`. + +We are going to keep the same logic as in our previous 'ping pong' example, but just repackage +it slightly differently. + +In this file we keep only the ping (main) side: + +``` javascript +// Creating the worker thread +var Threads = require('webworker-threads'); +var t = Threads.create(); + +// Listening to 'data' events from the worker thread +t.on('data', function(n, result) { + console.log('fibo(' + n + ') = ' + result); + if (n < 40) t.emit('next'); + else console.log('bye!'), t.destroy(); +}); +``` + +At this point we load the worker code: + +``` javascript +t.load(__dirname + '/ex04_worker.js'); +``` + +And we start the game by emitting the first `next` event: + +``` javascript +t.emit('next'); +``` + +### Output + +``` +fibo(1) = 1 +fibo(2) = 2 +fibo(3) = 3 +fibo(4) = 5 +... +fibo(39) = 102334155 +fibo(40) = 165580141 +bye! +``` diff --git a/node_modules/webworker-threads/examples/ex04_worker.js b/node_modules/webworker-threads/examples/ex04_worker.js new file mode 100644 index 0000000..4a784e6 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex04_worker.js @@ -0,0 +1,15 @@ +/// !example +/// ## Loading the worker code from a file (worker side) +/// +/// This file contains the pong (worker) side of our ping pong example. +/// It is loaded by a `t.load` call in `ex4_main.js`. +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +// returning the next fibonacci number when a 'next' event comes in: +var i = 1; +thread.on('next', function() { + thread.emit('data', i, fibo(i)); + i++; +});
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex04_worker.md b/node_modules/webworker-threads/examples/ex04_worker.md new file mode 100644 index 0000000..1304675 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex04_worker.md @@ -0,0 +1,18 @@ +## Loading the worker code from a file (worker side) + +This file contains the pong (worker) side of our ping pong example. +It is loaded by a `t.load` call in `ex4_main.js`. + +``` javascript +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +// returning the next fibonacci number when a 'next' event comes in: +var i = 1; +thread.on('next', function() { + thread.emit('data', i, fibo(i)); + i++; +}); +``` + diff --git a/node_modules/webworker-threads/examples/ex05_pool.js b/node_modules/webworker-threads/examples/ex05_pool.js new file mode 100644 index 0000000..f9ce4d8 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex05_pool.js @@ -0,0 +1,52 @@ +/// !example +/// ## Using the thread pool +/// +/// Our previous examples used a single worker thread, and thus only one processor core. +/// If we want to take full advantage of multi-core processors, we need the ability to delegate +/// expensive computations to a pool of theads. This example demonstrates the pool thread that comes +/// bundled with Worker. +/// +/// First, we create a pool +var Threads = require('webworker-threads'); +var pool = Threads.createPool(3); +/// +/// Then we load our fibonacci function in all the pool's threads: +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +pool.all.eval(fibo); +/// Now, we can get fibonacci numbers from our pool +/// +/// We request them in reverse order, to show that longer computations (`fibo(40)`) run in +/// parallel with shorter ones (`fibo(39)`, `fibo(38)`, ...). The results won't come out in strictly decreasing order. +var remain = 11; +for (var i = 40; i >= 30; i--) { + // extra closure to get proper scoping on 'i' + (function(i) { + // dispatch each request to the first available thread + pool.any.eval('fibo(' + i + ')', function(err, val) { + console.log('fibo(' + i + ')=' + i); + // destroy the pool when all results have been produced + if (--remain == 0) console.log('bye!'), pool.destroy(); + }); + })(i); +} +/// ### Typical (*) Output +/// +/// (*) Execution is non-deterministic. So order may vary. +/// +/// ``` +/// fibo(38)=38 +/// fibo(39)=39 +/// fibo(37)=37 +/// fibo(35)=35 +/// fibo(36)=36 +/// fibo(33)=33 +/// fibo(34)=34 +/// fibo(31)=31 +/// fibo(32)=32 +/// fibo(30)=30 +/// fibo(40)=40 +/// bye! +/// ```
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex05_pool.md b/node_modules/webworker-threads/examples/ex05_pool.md new file mode 100644 index 0000000..528793f --- /dev/null +++ b/node_modules/webworker-threads/examples/ex05_pool.md @@ -0,0 +1,63 @@ +## Using the thread pool + +Our previous examples used a single worker thread, and thus only one processor core. +If we want to take full advantage of multi-core processors, we need the ability to delegate +expensive computations to a pool of theads. This example demonstrates the pool thread that comes +bundled with webworker-threads. + +First, we create a pool + +``` javascript +var Threads = require('webworker-threads'); +var pool = Threads.createPool(3); +``` + + +Then we load our fibonacci function in all the pool's threads: + +``` javascript +function fibo(n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +pool.all.eval(fibo); +``` + +Now, we can get fibonacci numbers from our pool + +We request them in reverse order, to show that longer computations (`fibo(40)`) run in +parallel with shorter ones (`fibo(39)`, `fibo(38)`, ...). The results won't come out in strictly decreasing order. + +``` javascript +var remain = 11; +for (var i = 40; i >= 30; i--) { + // extra closure to get proper scoping on 'i' + (function(i) { + // dispatch each request to the first available thread + pool.any.eval('fibo(' + i + ')', function(err, val) { + console.log('fibo(' + i + ')=' + i); + // destroy the pool when all results have been produced + if (--remain == 0) console.log('bye!'), pool.destroy(); + }); + })(i); +} +``` + +### Typical (*) Output + +(*) Execution is non-deterministic. So order may vary. + +``` +fibo(38)=38 +fibo(39)=39 +fibo(37)=37 +fibo(35)=35 +fibo(36)=36 +fibo(33)=33 +fibo(34)=34 +fibo(31)=31 +fibo(32)=32 +fibo(30)=30 +fibo(40)=40 +bye! +``` diff --git a/node_modules/webworker-threads/examples/ex06_complex.js b/node_modules/webworker-threads/examples/ex06_complex.js new file mode 100644 index 0000000..d8d71b4 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex06_complex.js @@ -0,0 +1,39 @@ +/// A very simple class for complex numbers + +function Complex (x, y) { + this.x = x; + this.y = y; + this.add= complex_add; + this.mul= complex_mul; + this.toString= complex_toString; +} +function complex_toString () { + return this.x + (this.y > 0 ? " + " + this.y + "i" : this.y < 0 ? " - " + -this.y + "i" : ""); +} +function complex_add (c) { + return new Complex(this.x + c.x, this.y + c.y); +} +function complex_mul (c) { + return new Complex(this.x * c.x - this.y * c.y, this.x + c.y + this.y * c.x); +} + +/// A class to represent a degree 2 polynomial equation with real coefficients. + +function Equation (a, b, c) { + this.a = a; + this.b = b; + this.c = c; + this.toString= equation_toString; + this.solve= equation_solve; +} +function equation_toString () { + return this.a + "x^2 + " + this.b + "x + " + this.c +} +function equation_solve () { + var a = this.a, b = this.b, c = this.c + var det = b * b - 4 * a * c; + var sdet = Math.sqrt(Math.abs(det)); + var _2a = 2 * a; + if (det >= 0) return [new Complex((-b - sdet) / _2a, 0), new Complex((-b + sdet) / _2a, 0)]; + else return [new Complex(-b / _2a, -sdet / _2a), new Complex(-b / _2a, sdet / _2a)]; +}
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex06_jason.js b/node_modules/webworker-threads/examples/ex06_jason.js new file mode 100644 index 0000000..94c9474 --- /dev/null +++ b/node_modules/webworker-threads/examples/ex06_jason.js @@ -0,0 +1,42 @@ +/// !example +/// ## Passing complex objects to threads +/// +/// In the previous examples, we have been using threads with very simple functions and +/// we have been passing very simple values (integers) between threads. +/// +/// This example shows how we can pass more complex data between threads. +/// +/// It is important to understand that objects cannot be shared across threads. +/// This does not prevent us from passing complex objects but we have to serialize them +/// and pass them as strings. +/// +/// If the objects are really simple, we can use JSON serialization but if they contain +/// information that JSON discards, like methods, we should use the JASON serializer +/// published on https://github.com/xk/JASON +/// +/// In this example, we are going to use a thread to do computation with complex numbers. +/// We use the Complex and Equation classes defined in the ex06_complex.js file. +var Equation = require("./ex06_complex").Equation; +/// As usual, we create a thread +var t = require('webworker-threads').create(); +/// We require the JASON serializer +var JASON = require("JASON"); +/// We load the JASON serializer and the solve function in our thread: +t.eval("JASON= "+ JASON.stringify(JASON)); +t.load(__dirname + "/ex06_complex.js"); +/// Now we can pass a request to solve an equation to our thread. +/// The expression is wrapped into a `JASON.stringify` call because we want the thread +/// to stringify the solution object before returning it to the main thread +/// The main thread calls `JASON.parse` to _de-stringify_ the solution. +t.eval("JASON.stringify(new Equation(1, -4, 29).solve())", function(err, result) { + if (err) throw err; + var r = JASON.parse(result).join(', '); + console.log("\nsolution is:\n[" + r+ "]\n"); + t.destroy(); +}); +/// ### Typical Output +/// +/// ``` +/// solution is: +/// [2 - 5i, 2 + 5i] +/// ```
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/ex06_jason.md b/node_modules/webworker-threads/examples/ex06_jason.md new file mode 100644 index 0000000..000c3af --- /dev/null +++ b/node_modules/webworker-threads/examples/ex06_jason.md @@ -0,0 +1,61 @@ +## Passing complex objects to threads + +In the previous examples, we have been using threads with very simple functions and +we have been passing very simple values (integers) between threads. + +This example shows how we can pass more complex data between threads. + +It is important to understand that objects cannot be shared across threads. +This does not prevent us from passing complex objects but we have to serialize them +and pass them as strings. + +If the objects are really simple, we can use JSON serialization but if they contain +information that JSON discards, like methods, we should use the JASON serializer +published on https://github.com/xk/JASON + +In this example, we are going to use a thread to do computation with complex numbers. +We use the Complex and Equation classes defined in the ex06_complex.js file. + +``` javascript +var Equation = require("./ex06_complex").Equation; +``` + +As usual, we create a thread + +``` javascript +var t = require('webworker-threads').create(); +``` + +We require the JASON serializer + +``` javascript +var JASON = require("JASON"); +``` + +We load the JASON serializer and the solve function in our thread: + +``` javascript +t.eval("JASON= "+ JASON.stringify(JASON)); +t.load(__dirname + "/ex06_complex.js") +``` + +Now we can pass a request to solve an equation to our thread. +The expression is wrapped into a `JASON.stringify` call because we want the thread +to stringify the solution object before returning it to the main thread +The main thread calls `JASON.parse` to _de-stringify_ the solution. + +``` javascript +t.eval("JASON.stringify(new Equation(1, -4, 29).solve())", function(err, result) { + if (err) throw err; + var r = JASON.parse(result).join(', '); + console.log("\nsolution is:\n[" + r+ "]\n"); + t.destroy(); +}); +``` + +### Typical Output + +``` +solution is: +[2 - 5i, 2 + 5i] +``` diff --git a/node_modules/webworker-threads/examples/fiveThreads.ls b/node_modules/webworker-threads/examples/fiveThreads.ls new file mode 100755 index 0000000..9d8b324 --- /dev/null +++ b/node_modules/webworker-threads/examples/fiveThreads.ls @@ -0,0 +1,15 @@ +#!/usr/bin/env lsc +# Same as multiThreadEvented.ls, but with 5 workers + +{ Worker } = require \webworker-threads + +for til 5 => (new Worker -> + fibo = (n) -> if n > 1 then fibo(n - 1) + fibo(n - 2) else 1 + @onmessage = ({ data }) -> postMessage fibo data +) + ..onmessage = ({ data }) -> + console.log "[#{ @thread.id }] #data" + @postMessage Math.ceil Math.random! * 30 + ..postMessage Math.ceil Math.random! * 30 + +do spin = -> process.nextTick spin diff --git a/node_modules/webworker-threads/examples/multiThreadEvented.ls b/node_modules/webworker-threads/examples/multiThreadEvented.ls new file mode 100755 index 0000000..982c1dd --- /dev/null +++ b/node_modules/webworker-threads/examples/multiThreadEvented.ls @@ -0,0 +1,15 @@ +#!/usr/bin/env lsc +# Minimal example for https://npmjs.org/package/webworker-threads + +{ Worker } = require \webworker-threads + +(new Worker -> + fibo = (n) -> if n > 1 then fibo(n - 1) + fibo(n - 2) else 1 + @onmessage = ({ data }) -> postMessage fibo data +) + ..onmessage = ({ data }) -> + console.log data + @postMessage Math.ceil Math.random! * 30 + ..postMessage Math.ceil Math.random! * 30 + +do spin = -> process.nextTick spin diff --git a/node_modules/webworker-threads/examples/quickIntro_blocking.js b/node_modules/webworker-threads/examples/quickIntro_blocking.js new file mode 100644 index 0000000..fedb97f --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_blocking.js @@ -0,0 +1,13 @@ +function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +(function fiboLoop () { + process.stdout.write(fibo(35).toString()); + process.nextTick(fiboLoop); +})(); + +(function spinForever () { + process.stdout.write("."); + process.nextTick(spinForever); +})(); diff --git a/node_modules/webworker-threads/examples/quickIntro_evented_childThreadCode.js b/node_modules/webworker-threads/examples/quickIntro_evented_childThreadCode.js new file mode 100644 index 0000000..ba31205 --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_evented_childThreadCode.js @@ -0,0 +1,7 @@ +function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +thread.on('giveMeTheFibo', function onGiveMeTheFibo (data) { + this.emit('theFiboIs', fibo(+data)); //Emits 'theFiboIs' in the parent/main thread. +});
\ No newline at end of file diff --git a/node_modules/webworker-threads/examples/quickIntro_fiveThreads.js b/node_modules/webworker-threads/examples/quickIntro_fiveThreads.js new file mode 100644 index 0000000..1348a97 --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_fiveThreads.js @@ -0,0 +1,21 @@ +function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +function cb (err, data) { + process.stdout.write(" ["+ this.id+ "]"+ data); + this.eval('fibo(35)', cb); +} + +var Worker= require('webworker-threads'); + +Worker.create().eval(fibo).eval('fibo(35)', cb); +Worker.create().eval(fibo).eval('fibo(35)', cb); +Worker.create().eval(fibo).eval('fibo(35)', cb); +Worker.create().eval(fibo).eval('fibo(35)', cb); +Worker.create().eval(fibo).eval('fibo(35)', cb); + +(function spinForever () { + process.stdout.write("."); + process.nextTick(spinForever); +})(); diff --git a/node_modules/webworker-threads/examples/quickIntro_loop.js b/node_modules/webworker-threads/examples/quickIntro_loop.js new file mode 100644 index 0000000..4d4212c --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_loop.js @@ -0,0 +1,4 @@ +(function spinForever () { + process.stdout.write("."); + process.nextTick(spinForever); +})(); diff --git a/node_modules/webworker-threads/examples/quickIntro_multiThread.js b/node_modules/webworker-threads/examples/quickIntro_multiThread.js new file mode 100644 index 0000000..86e861e --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_multiThread.js @@ -0,0 +1,16 @@ +function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +var numThreads= 10; +var threadPool= require('webworker-threads').createPool(numThreads).all.eval(fibo); + +threadPool.all.eval('fibo(35)', function cb (err, data) { + process.stdout.write(" ["+ this.id+ "]"+ data); + this.eval('fibo(35)', cb); +}); + +(function spinForever () { + process.stdout.write("."); + process.nextTick(spinForever); +})(); diff --git a/node_modules/webworker-threads/examples/quickIntro_multiThreadEvented.js b/node_modules/webworker-threads/examples/quickIntro_multiThreadEvented.js new file mode 100644 index 0000000..bd7f4c1 --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_multiThreadEvented.js @@ -0,0 +1,30 @@ +var numThreads= 10; +var threadPool= require('webworker-threads').createPool(numThreads); +threadPool.load(__dirname + '/quickIntro_evented_childThreadCode.js'); + +/* + This is the code that's .load()ed into the child/background threads: + + function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; + } + + thread.on('giveMeTheFibo', function onGiveMeTheFibo (data) { + this.emit('theFiboIs', fibo(+data)); //Emits 'theFiboIs' in the parent/main thread. + }); + +*/ + +//Emit 'giveMeTheFibo' in all the child/background threads. +threadPool.all.emit('giveMeTheFibo', 35); + +//Listener for the 'theFiboIs' events emitted by the child/background thread. +threadPool.on('theFiboIs', function cb (data) { + process.stdout.write(" ["+ this.id+ "]"+ data); + this.emit('giveMeTheFibo', 35); +}); + +(function spinForever () { + process.stdout.write("."); + process.nextTick(spinForever); +})(); diff --git a/node_modules/webworker-threads/examples/quickIntro_oneThread.js b/node_modules/webworker-threads/examples/quickIntro_oneThread.js new file mode 100644 index 0000000..82f342d --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_oneThread.js @@ -0,0 +1,17 @@ +function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; +} + +function cb (err, data) { + process.stdout.write(data); + this.eval('fibo(35)', cb); +} + +var thread= require('webworker-threads').create(); + +thread.eval(fibo).eval('fibo(35)', cb); + +(function spinForever () { + process.stdout.write("."); + process.nextTick(spinForever); +})(); diff --git a/node_modules/webworker-threads/examples/quickIntro_oneThreadEvented.js b/node_modules/webworker-threads/examples/quickIntro_oneThreadEvented.js new file mode 100644 index 0000000..fed6f41 --- /dev/null +++ b/node_modules/webworker-threads/examples/quickIntro_oneThreadEvented.js @@ -0,0 +1,18 @@ +var Worker = require('webworker-threads').Worker; +var w = new Worker(function(){ + function fibo (n) { + return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; + } + self.onmessage = function (event) { + self.postMessage( fibo( event.data ) ); + }; +}); +w.postMessage(Math.ceil(Math.random()*30)); +w.onmessage = function cb (event) { + process.stdout.write(event.data); + w.postMessage(Math.ceil(Math.random()*30)); +}; +(function spinForever () { + process.stdout.write("."); + process.nextTick(spinForever); +})(); |
