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