Module jls.util.Worker
Provides a way to process tasks in background.
The worker thread interacts with the current thread via message passing.
By default the worker thread has an event loop and will be triggered when receiving message.
You could disable the event loop and incoming messages by using the option disableReceive.
Class Worker
| Worker:new (fn[, data[, onMessage[, options]]]) | Creates a new Worker. |
| worker:postMessage (message) | Sends a message to the worker. |
| worker:onMessage (message) | Receives a message from the worker. |
| worker:isConnected () | Returns true if this worker is connected. |
| worker:close () | Closes the worker. |
Class Worker
The Worker class.
The Worker provides a way to process task in background.
- Worker:new (fn[, data[, onMessage[, options]]])
-
Creates a new Worker.
Parameters:
- fn function the function that the worker will execute
- data the data to pass to the worker function (optional)
- onMessage function the function that will handle messages (optional)
- options table the worker options (optional)
Returns:
-
a new Worker
Usage:
local w = Worker:new(function(w) function w:onMessage(message) print('received in worker', message) w:postMessage('Hi '..tostring(message)) end end, nil, function(self, message) print('received from worker', message) self:close() end) w:postMessage('John')
- worker:postMessage (message)
-
Sends a message to the worker.
Parameters:
- message the message to send
Returns:
-
jls.lang.Promise
a promise that resolves once the message is sent
- worker:onMessage (message)
-
Receives a message from the worker.
Parameters:
- message the message to handle
- worker:isConnected ()
-
Returns true if this worker is connected.
Returns:
-
boolean
true if this worker is connected
- worker:close ()
- Closes the worker.