Skip to content
maxless edited this page Dec 14, 2015 · 3 revisions

Worker

The cache server has a single asynchronous worker thread. The slave server has that functionality expanded. The snipe.slave.Worker class allows the creation of multiple asynchronous workers that each have their own thread. The thread waits until the message queue has some tasks to run. The API closely resembles the snipe.cache.AsyncWorker class.

Let's take a look at full example. The module in the example has a calculate() API method that receives some parameters, passes them to the worker thread, does the work there, and returns them to the main thread.

import snipe.slave.Worker;

class CalcModule extends snipe.slave.Module<Client, ServerTest>
{
  var _worker: Worker;

  public function new(srv: ServerTest)
    {
      super(srv);

      // ...

      _worker = new Worker(srv, 'calc');
    }

  public function calculate(params: CalcParams)
    {
      _worker.call('calc.time', params, calculateWorker, calculateMain);
    }

  function calculateWorker(params: CalcParams)
    {
      for (0...1000)
        params.z = params.x + params.y;
    }

  function calculateMain(params: CalcParams)
    {
      var client = server.getClient(params.id, true);
      if (client == null)
        return;

      client.calculatedZ(params.z);
    }
}

The calculateWorker method will run in the worker thread, then pass the parameters object to the calculateMain method that will run in the main server thread. Note that you should be extra careful, we pass the client ID into the worker because while it works, the client can be disconnected. Also since the worker thread is different from the main thread, we cannot modify the client there. In general, all the limitations and problems of the multithreaded programming apply here.

Clone this wiki locally