Compare commits

..

No commits in common. 'dev' and 'dev-asio-engine' have entirely different histories.

  1. 60
      README.md
  2. 65
      lib/event.hpp
  3. 44
      lib/timers.hpp
  4. 92
      lib/trigger.hpp
  5. 146
      test/test.cpp

@ -3,12 +3,6 @@
A C++ library for event-driven asynchronous multi-threaded programming. A C++ library for event-driven asynchronous multi-threaded programming.
## Motivation
The original concept was to create an interface capable of asynchronously calling any function. It has since evolved into a library that incorporates a thread pool, each with its own event loop, event-driven programming, and functions inherently designed for asynchronous operation (including periodic and delayed functions).
The asynchronous filesystem is provided solely to guide users on how to wrap any time- or IO-intensive function for asynchronous execution.
## Features ## Features
- Object oriented - Object oriented
@ -16,8 +10,8 @@ The asynchronous filesystem is provided solely to guide users on how to wrap any
- Header only - Header only
- Asynchronous programming - Asynchronous programming
- Multithread - Multithread
- Asynchronous timer functions: periodic, delayed (like setInterval and setTimeout from JS) - Asynchronous timer functions: interval, timeout
- Typed events (on, tick, off) (like EventEmitter from JS: on, emit, etc) - Typed events (on, emit, off)
- Event loops - Event loops
- Multiple parallel execution loops - Multiple parallel execution loops
- Asynchronous file IO - Asynchronous file IO
@ -29,14 +23,14 @@ Just download the latest release and unzip it into your project.
```c++ ```c++
#define NUM_OF_RUNNERS 8 // To change the number of threads used by atask, without this it runs according to the number of cores #define NUM_OF_RUNNERS 8 // To change the number of threads used by atask, without this it runs according to the number of cores
#include "asynco/lib/asynco.hpp" // atask(), wait() #include "asynco/lib/asynco.hpp" // atask(), wait()
#include "asynco/lib/triggers.hpp" // trigger (event emitter) #include "asynco/lib/event.hpp" // event
#include "asynco/lib/timers.hpp" // periodic, delayed (like setInterval and setTimeout from JS) #include "asynco/lib/timers.hpp" // interval, timeout
#include "asynco/lib/filesystem.hpp" // for async read and write files #include "asynco/lib/filesystem.hpp" // for async read and write files
using namespace marcelb; using namespace marcelb;
using namespace asynco; using namespace asynco;
using namespace triggers; using namespace events;
// At the end of the main function, always set // At the end of the main function, always set
_asynco_engine.run(); _asynco_engine.run();
@ -49,12 +43,12 @@ return 0;
Time asynchronous functions Time asynchronous functions
```c++ ```c++
// start periodic // start interval
periodic inter1 ([]() { interval inter1 ([]() {
cout << "Interval 1" << endl; cout << "Interval 1" << endl;
}, 1000); }, 1000);
// stop periodic // stop interval
inter1.stop(); inter1.stop();
// how many times it has expired // how many times it has expired
@ -63,12 +57,12 @@ int t = inter1.ticks();
// is it stopped // is it stopped
bool stoped = inter1.stoped(); bool stoped = inter1.stoped();
// start delayed // start timeout
delayed time1 ( [] () { timeout time1 ( [] () {
cout << "Timeout 1 " << endl; cout << "Timeout 1 " << endl;
}, 10000); }, 10000);
// stop delayed // stop timeout
time1.stop(); time1.stop();
// is it expired // is it expired
@ -143,12 +137,12 @@ cout << wait(atask( [] () {
})) << endl; })) << endl;
/** /**
* Sleep with delayed sleep implement * Sleep with timeout sleep implement
*/ */
void sleep_to (int _time) { void sleep_to (int _time) {
promise<void> _promise; promise<void> _promise;
delayed t( [&]() { timeout t( [&]() {
_promise.set_value(); _promise.set_value();
}, _time); }, _time);
@ -163,7 +157,7 @@ sleep_to(3000);
void promise_reject (int _time) { void promise_reject (int _time) {
promise<void> _promise; promise<void> _promise;
delayed t( [&]() { timeout t( [&]() {
try { try {
// simulate except // simulate except
throw runtime_error("Error simulation"); throw runtime_error("Error simulation");
@ -189,9 +183,9 @@ Events
* initialization of typed events * initialization of typed events
*/ */
trigger<int, int> ev2int; event<int, int> ev2int;
trigger<int, string> evintString; event<int, string> evintString;
trigger<> evoid; event<> evoid;
ev2int.on("sum", [](int a, int b) { ev2int.on("sum", [](int a, int b) {
cout << "Sum " << a+b << endl; cout << "Sum " << a+b << endl;
@ -219,32 +213,32 @@ sleep(1);
* Emit * Emit
*/ */
ev2int.tick("sum", 5, 8); ev2int.emit("sum", 5, 8);
sleep(1); sleep(1);
evintString.tick("substract", 3, to_string(2)); evintString.emit("substract", 3, to_string(2));
sleep(1); sleep(1);
evoid.tick("void"); evoid.emit("void");
// Turn off the event listener // Turn off the event listener
evoid.off("void"); evoid.off("void");
evoid.tick("void"); // nothing is happening evoid.emit("void"); // nothing is happening
``` ```
Extend own class whit events Extend own class whit events
```c++ ```c++
class myOwnClass : public trigger<int> { class myOwnClass : public event<int> {
public: public:
myOwnClass() : trigger() {}; myOwnClass() : event() {};
}; };
myOwnClass myclass; myOwnClass myclass;
delayed t( [&] { timeout t( [&] {
myclass.tick("constructed", 1); myclass.emit("constructed", 1);
}, 200); }, 200);
myclass.on("constructed", [] (int i) { myclass.on("constructed", [] (int i) {

@ -0,0 +1,65 @@
#ifndef _EVENT_
#define _EVENT_
#include <map>
#include <vector>
#include <string>
#include <functional>
using namespace std;
#include "asynco.hpp"
namespace marcelb {
namespace asynco {
namespace events {
/**
* Event class, for event-driven programming.
* These events are typed according to the arguments of the callback function
*/
template<typename... T>
class event {
private:
mutex m_eve;
unordered_map<string, vector<function<void(T...)>>> events;
public:
/**
* Defines event by key, and callback function
*/
void on(const string& key, function<void(T...)> callback) {
lock_guard _off(m_eve);
events[key].push_back(callback);
}
/**
* It emits an event and sends a callback function saved according to the key with the passed parameters
*/
template<typename... Args>
void emit(const string& key, Args... args) {
auto it_eve = events.find(key);
if (it_eve != events.end()) {
for (uint i =0; i<it_eve->second.size(); i++) {
auto callback = bind(it_eve->second[i], forward<Args>(args)...);
atask(callback);
}
}
}
/**
* Remove an event listener from an event
*/
void off(const string& key) {
lock_guard _off(m_eve);
events.erase(key);
}
};
}
}
}
#endif

@ -1,5 +1,5 @@
#ifndef _TIMERS_ #ifndef _ROTOR_
#define _TIMERS_ #define _ROTOT_
#include "asynco.hpp" #include "asynco.hpp"
#include <chrono> #include <chrono>
@ -113,22 +113,22 @@ class timer {
}; };
/** /**
* Class periodic for periodic execution of the callback in time in ms * Class interval for periodic execution of the callback in time in ms
*/ */
class periodic { class interval {
shared_ptr<timer> _timer; shared_ptr<timer> _timer;
public: public:
/** /**
* Constructor initializes a shared pointer of type timer * Constructor initializes a shared pointer of type timer
*/ */
periodic(function<void()> callback, uint64_t time) : interval(function<void()> callback, uint64_t time) :
_timer(make_shared<timer> (callback, time, true)) { _timer(make_shared<timer> (callback, time, true)) {
} }
/** /**
* Stop periodic * Stop interval
* The stop flag is set and periodic remove it from the queue * The stop flag is set and interval remove it from the queue
*/ */
void stop() { void stop() {
_timer->stop(); _timer->stop();
@ -136,51 +136,51 @@ class periodic {
/** /**
* Run callback now * Run callback now
* Forces the callback function to run independently of the periodic * Forces the callback function to run independently of the interval
*/ */
void now() { void now() {
_timer->now(); _timer->now();
} }
/** /**
* Get the number of times the periodic callback was runned * Get the number of times the interval callback was runned
*/ */
uint64_t ticks() { uint64_t ticks() {
return _timer->ticks(); return _timer->ticks();
} }
/** /**
* The logic status of the periodic stop state * The logic status of the interval stop state
*/ */
bool stoped() { bool stoped() {
return _timer->stoped(); return _timer->stoped();
} }
/** /**
* The destructor stops the periodic * The destructor stops the interval
*/ */
~periodic() { ~interval() {
stop(); stop();
} }
}; };
/** /**
* Class delayed for delayed callback execution in ms * Class timeout for delayed callback execution in ms
*/ */
class delayed { class timeout {
shared_ptr<timer> _timer; shared_ptr<timer> _timer;
public: public:
/** /**
* Constructor initializes a shared pointer of type timer * Constructor initializes a shared pointer of type timer
*/ */
delayed(function<void()> callback, uint64_t time) : timeout(function<void()> callback, uint64_t time) :
_timer(make_shared<timer> (callback, time, false)) { _timer(make_shared<timer> (callback, time, false)) {
} }
/** /**
* Stop delayed * Stop timeout
* The stop flag is set and delayed remove it from the queue * The stop flag is set and timeout remove it from the queue
*/ */
void stop() { void stop() {
_timer->stop(); _timer->stop();
@ -188,30 +188,30 @@ class delayed {
/** /**
* Run callback now * Run callback now
* Forces the callback function to run independently of the delayed * Forces the callback function to run independently of the timeout
*/ */
void now() { void now() {
_timer->now(); _timer->now();
} }
/** /**
* Get is the delayed callback runned * Get the number of times the timeout callback was runned
*/ */
bool expired() { bool expired() {
return bool(_timer->ticks()); return bool(_timer->ticks());
} }
/** /**
* The logic status of the delayed stop state * The logic status of the timeout stop state
*/ */
bool stoped() { bool stoped() {
return _timer->stoped(); return _timer->stoped();
} }
/** /**
* The destructor stops the delayed * The destructor stops the timeout
*/ */
~delayed() { ~timeout() {
stop(); stop();
} }

@ -1,92 +0,0 @@
#ifndef _TRIGGER_
#define _TRIGGER_
#include <map>
#include <vector>
#include <string>
#include <functional>
using namespace std;
#include "asynco.hpp"
namespace marcelb {
namespace asynco {
namespace triggers {
/**
* trigger class, for event-driven programming.
* These events are typed according to the arguments of the callback function
*/
template<typename... T>
class trigger {
private:
mutex m_eve;
unordered_map<string, vector<function<void(T...)>>> triggers;
public:
/**
* Defines event by key, and callback function
*/
void on(const string& key, function<void(T...)> callback) {
lock_guard _off(m_eve);
triggers[key].push_back(callback);
}
/**
* It emits an event and sends a callback function saved according to the key with the passed parameters
*/
template<typename... Args>
void tick(const string& key, Args... args) {
auto it_eve = triggers.find(key);
if (it_eve != triggers.end()) {
for (uint i =0; i<it_eve->second.size(); i++) {
auto callback = bind(it_eve->second[i], forward<Args>(args)...);
atask(callback);
}
}
}
/**
* Remove an trigger listener from an event
*/
void off(const string& key) {
lock_guard _off(m_eve);
triggers.erase(key);
}
/**
* Remove all trigger listener
*/
void off() {
lock_guard _off(m_eve);
triggers.clear();
}
/**
* Get num of listeners by an trigger key
*/
unsigned int listeners(const string& key) {
return triggers[key].size();
}
/**
* Get num of all listeners
*/
unsigned int listeners() {
unsigned int listeners = 0;
for (auto& ev : triggers) {
listeners += ev.second.size();
}
return listeners;
}
};
}
}
}
#endif

@ -1,12 +1,12 @@
// // #define NUM_OF_RUNNERS 2 // #define NUM_OF_RUNNERS 2
#include "../lib/asynco.hpp" #include "../lib/asynco.hpp"
#include "../lib/trigger.hpp" #include "../lib/event.hpp"
#include "../lib/filesystem.hpp" #include "../lib/filesystem.hpp"
#include "../lib/timers.hpp" #include "../lib/timers.hpp"
using namespace marcelb::asynco; using namespace marcelb::asynco;
using namespace triggers; using namespace events;
#include <iostream> #include <iostream>
#include <unistd.h> #include <unistd.h>
@ -18,7 +18,7 @@ using namespace this_thread;
void sleep_to (int _time) { void sleep_to (int _time) {
promise<void> _promise; promise<void> _promise;
delayed t( [&]() { timeout t( [&]() {
_promise.set_value(); _promise.set_value();
}, _time); }, _time);
@ -27,7 +27,7 @@ void sleep_to (int _time) {
void promise_reject (int _time) { void promise_reject (int _time) {
promise<void> _promise; promise<void> _promise;
delayed t( [&]() { timeout t( [&]() {
try { try {
// simulate except // simulate except
throw runtime_error("Error simulation"); throw runtime_error("Error simulation");
@ -53,9 +53,9 @@ class clm {
// ------------------ EXTEND OWN CLASS WITH EVENTS ------------------- // ------------------ EXTEND OWN CLASS WITH EVENTS -------------------
class myOwnClass : public trigger<int> { class myOwnClass : public event<int> {
public: public:
myOwnClass() : trigger() {}; myOwnClass() : event() {};
}; };
@ -66,36 +66,36 @@ int main () {
// --------------- TIME ASYNCHRONOUS FUNCTIONS -------------- // --------------- TIME ASYNCHRONOUS FUNCTIONS --------------
// /** // /**
// * Init periodic and delayed; clear periodic and delayed // * Init interval and timeout; clear interval and timeout
// */ // */
// periodic inter1 ([&]() { // interval inter1 ([&]() {
// cout << "periodic prvi " << rtime_ms() - start << endl; // cout << "interval prvi " << rtime_ms() - start << endl;
// }, 1000); // }, 1000);
// periodic inter2 ([&]() { // interval inter2 ([&]() {
// cout << "periodic drugi " << rtime_ms() - start << endl; // cout << "interval drugi " << rtime_ms() - start << endl;
// }, 2000); // }, 2000);
// periodic inter3 ([&]() { // interval inter3 ([&]() {
// cout << "periodic treći " << rtime_ms() - start << endl; // cout << "interval treći " << rtime_ms() - start << endl;
// }, 1000); // }, 1000);
// periodic inter4 ([&]() { // interval inter4 ([&]() {
// // cout << "periodic cetvrti " << rtime_ms() - start << endl; // // cout << "interval cetvrti " << rtime_ms() - start << endl;
// cout << "Ticks " << inter3.ticks() << endl; // cout << "Ticks " << inter3.ticks() << endl;
// }, 500); // }, 500);
// periodic inter5 ([&]() { // interval inter5 ([&]() {
// cout << "periodic peti " << rtime_ms() - start << endl; // cout << "interval peti " << rtime_ms() - start << endl;
// }, 2000); // }, 2000);
// periodic inter6 ([&]() { // interval inter6 ([&]() {
// cout << "periodic sesti " << rtime_ms() - start << endl; // cout << "interval sesti " << rtime_ms() - start << endl;
// }, 3000); // }, 3000);
// delayed time1 ( [&] () { // timeout time1 ( [&] () {
// cout << "Close periodic 1 i 2 " << rtime_ms() - start << endl; // cout << "Close interval 1 i 2 " << rtime_ms() - start << endl;
// inter1.stop(); // inter1.stop();
// cout << "inter1.stop " << endl; // cout << "inter1.stop " << endl;
// inter2.stop(); // inter2.stop();
@ -103,8 +103,8 @@ int main () {
// }, 8000); // }, 8000);
// delayed time2 ([&] () { // timeout time2 ([&] () {
// cout << "Close periodic 3 " << rtime_ms() - start << endl; // cout << "Close interval 3 " << rtime_ms() - start << endl;
// inter3.stop(); // inter3.stop();
// cout << "Stoped " << inter3.stoped() << endl; // cout << "Stoped " << inter3.stoped() << endl;
// // time1.stop(); // // time1.stop();
@ -185,7 +185,7 @@ int main () {
// })) << endl; // })) << endl;
// /** // /**
// * Sleep with delayed sleep implement // * Sleep with timeout sleep implement
// */ // */
// sleep_to(3000); // sleep_to(3000);
@ -216,74 +216,68 @@ int main () {
// }); // });
// }); // });
// --------------- EVENTS ------------------- // // // --------------- EVENTS -------------------
/** // /**
* initialization of typed events // * initialization of typed events
*/ // */
trigger<int, int> ev2int; // event<int, int> ev2int;
trigger<int, string> evintString; // event<int, string> evintString;
trigger<> evoid; // event<> evoid;
ev2int.on("sum", [](int a, int b) { // ev2int.on("sum", [](int a, int b) {
cout << "Sum " << a+b << endl; // cout << "Sum " << a+b << endl;
}); // });
ev2int.on("sum", [](int a, int b) { // ev2int.on("sum", [](int a, int b) {
cout << "Sum done" << endl; // cout << "Sum done" << endl;
}); // });
evintString.on("substract", [](int a, string b) { // evintString.on("substract", [](int a, string b) {
cout << "Substract " << a-stoi(b) << endl; // cout << "Substract " << a-stoi(b) << endl;
}); // });
evoid.on("void", []() { // evoid.on("void", []() {
cout << "Void emited" << endl; // cout << "Void emited" << endl;
}); // });
string emited2 = "2"; // string emited2 = "2";
evoid.on("void", [&]() { // evoid.on("void", [&]() {
cout << "Void emited " << emited2 << endl; // cout << "Void emited " << emited2 << endl;
}); // });
evoid.tick("void"); // evoid.emit("void");
sleep(1); // sleep(1);
/** // /**
* Emit // * Emit
*/ // */
ev2int.tick("sum", 5, 8); // ev2int.emit("sum", 5, 8);
sleep(1); // sleep(1);
evintString.tick("substract", 3, to_string(2)); // evintString.emit("substract", 3, to_string(2));
sleep(1);
evoid.off("void");
evoid.tick("void");
cout << "Ukupno 2 int " << ev2int.listeners() << endl; // sleep(1);
cout << "Ukupno evintString " << evintString.listeners() << endl; // evoid.off("void");
cout << "Ukupno evoid " << evoid.listeners() << endl; // evoid.emit("void");
cout << "Ukupno 2 int " << ev2int.listeners("sum") << endl;
/** // /**
* Own class // * Own class
*/ // */
myOwnClass myclass; // myOwnClass myclass;
delayed t( [&] { // timeout t( [&] {
myclass.tick("constructed", 1); // myclass.emit("constructed", 1);
}, 200); // }, 200);
myclass.on("constructed", [] (int i) { // myclass.on("constructed", [] (int i) {
cout << "Constructed " << i << endl; // cout << "Constructed " << i << endl;
}); // });
@ -313,7 +307,7 @@ int main () {
// }); // });
// // ---------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------
cout << "Run" << endl; cout << "Run" << endl;
_asynco_engine.run(); _asynco_engine.run();

Loading…
Cancel
Save