UNPKG

1.82 kBMarkdownView Raw
1## Passing complex objects to threads
2
3In the previous examples, we have been using threads with very simple functions and
4we have been passing very simple values (integers) between threads.
5
6This example shows how we can pass more complex data between threads.
7
8It is important to understand that objects cannot be shared across threads.
9This does not prevent us from passing complex objects but we have to serialize them
10and pass them as strings.
11
12If the objects are really simple, we can use JSON serialization but if they contain
13information that JSON discards, like methods, we should use the JASON serializer
14published on https://github.com/xk/JASON
15
16In this example, we are going to use a thread to do computation with complex numbers.
17We use the Complex and Equation classes defined in the ex06_complex.js file.
18
19``` javascript
20var Equation = require("./ex06_complex").Equation;
21```
22
23As usual, we create a thread
24
25``` javascript
26var t = require('webworker-threads').create();
27```
28
29We require the JASON serializer
30
31``` javascript
32var JASON = require("JASON");
33```
34
35We load the JASON serializer and the solve function in our thread:
36
37``` javascript
38t.eval("JASON= "+ JASON.stringify(JASON));
39t.load(__dirname + "/ex06_complex.js")
40```
41
42Now we can pass a request to solve an equation to our thread.
43The expression is wrapped into a `JASON.stringify` call because we want the thread
44to stringify the solution object before returning it to the main thread
45The main thread calls `JASON.parse` to _de-stringify_ the solution.
46
47``` javascript
48t.eval("JASON.stringify(new Equation(1, -4, 29).solve())", function(err, result) {
49 if (err) throw err;
50 var r = JASON.parse(result).join(', ');
51 console.log("\nsolution is:\n[" + r+ "]\n");
52 t.destroy();
53});
54```
55
56### Typical Output
57
58```
59solution is:
60[2 - 5i, 2 + 5i]
61```