Skip to content
This repository has been archived by the owner on Jan 6, 2020. It is now read-only.

Active Object

dirvine edited this page Jun 25, 2013 · 8 revisions

Back ###Motivation To present an API that allows operations to be run synchronously in an ordered manner. This allows non thread safe functions to be run asynchronously. This is achieved by sending functors to be executed into a thread safe (or internally synchronised) queue and having a worker thread monitor that queue and run any functors stored there in a First In First Out (FIFO) order. Thread conditional variables are used to ensure the worker thread wakes and executes any tasks as any task is posted.

###Examples

#include <iostream>
#include <thread>
#include "maidsafe/active.h"

void Print(maidsafe::Active& active) {
  for(auto i(0); i < 100; ++i)
    active.send([] { std::cout << this is  a single line" << " continuing /n" });
}

void AlsoPrint(maidsafe::Active& active) {
  for(auto i(0); i < 100; ++i)
    active.send([] { std::cout << "Here is some more text" << " again/n" }); ;
}

int main() {
  maidsafe::Active active;
  std::thread t1(Print, active);
  std::thread t2(AlsoPrint, active);
  t1.join();
  t2.join();
  return 0;
}
// output is non interleaved 

###Reference maidsafe/active.h

// public interface
class Active {
 public:
  typedef std::function<void()> Functor;
  Active();
  ~Active();
  void Send(Functor functor);
private:
 ...
}

Back