Component v0.2.3 Component.Strategy.Dynamic View Source
Implement a service factory, which you can use to create any number of workers.
Usage
To create the service:
Create a module that implements the API you want. This API will be expressed as a set of public functions. Each function will automatically receive the current state in a variable (by default named
state
). There is not need to declare this as a parameter.why?. If a function wants to change the state, it must end with a call to theset_state/2
function (which will have been imported into your module automatically).For this example, we'll call the module
Workers
.Add the line
use Component.Strategy.Dynamic
to the top of this module.Adjust the other options if required.
To start the worker supervisor:
Workers.initialize()
or
Workers.initialize(initial_state)
Claim a worker using
worker = Workers.create()
Call functions in the module using
result = Workers.some_function(worker, other_args) ...
When you're finished with the worker, call
Workers.destroy(worker)
Example
defmodule FaceDetector do
using Component.Strategy.Dynamic
state: %{ algorithm: ViolaJones },
state_name: :options,
def recognize(image) do
# calls to OpenCV or whatever...
end
end
Options
You can pass a keyword list to use Component.Strategy.Dynamic
:
initial_state:
valueThe default value for the initial state of all workers. Can be overridden (again for all workers) by passing a value to
initialize()
state_name:
atomThe default name for the state variable is (unimaginatively)
state
. Usestate_name
to override this. For example, the previous example named the stateoptions
, and inside therecognize
function your could writeoptions.algorithm
to look up the algorithm to use.name:
atomThe default name for the pool is the name of the module that defines it. Use
name:
to change this.showcode:
booleanIf truthy, dump a representation of the generated code to STDOUT during compilation.
timeout:
integer or floatSpecify the timeout to be used when the client calls workers in the pool. If all workers are busy, and none becomes free in that time, an OTP exception is raised. An integer specifies the timeout in milliseconds, and a float in seconds (so 1.5 is the same as 1500).