Skip to content

Commit

Permalink
Changed it to vectors of callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
berndporr committed Feb 1, 2025
1 parent f313ff9 commit a4d1f20
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 27 deletions.
36 changes: 16 additions & 20 deletions CppTimerCallback.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,31 @@
#include <stdio.h>
#include "CppTimer.h"
#include <unistd.h>
#include <vector>

// Demo which creates a callback interface as the abstract class "Runnable".
// This then allows to register a callback.

class CppTimerCallback : public CppTimer {

public:
class Runnable {
public:
virtual void run() = 0;
};

void registerEventRunnable(Runnable &h) {
cppTimerEventRunnable = &h;
}

void unregisterEventRunnable() {
cppTimerEventRunnable = NULL;
}

void timerEvent() {
if (cppTimerEventRunnable) {
cppTimerEventRunnable->run();
}
class Runnable {
public:
virtual void run() = 0;
};

void registerEventRunnable(Runnable &h) {
cppTimerEventRunnables.push_back(&h);
}

void timerEvent() {
for(auto & r : cppTimerEventRunnables) {
r->run();
}
}

private:
Runnable* cppTimerEventRunnable = NULL;

std::vector<Runnable*> cppTimerEventRunnables;
};


Expand Down
9 changes: 5 additions & 4 deletions CppTimerStdFuncCallback.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "CppTimer.h"
#include <unistd.h>
#include <functional>
#include <vector>

// This is a demo how to create a callback with std::function which allows
// calling methods in other classes by registering a lambda function!
Expand All @@ -15,17 +16,17 @@ class CppTimerCallback : public CppTimer {
using CallbackFunction = std::function<void(void)>;

void registerEventCallback(CallbackFunction cf) {
callbackFunction = cf;
callbackFunctions.push_back(cf);
}

void timerEvent() {
if (nullptr != callbackFunction) {
callbackFunction();
for(auto &cb : callbackFunctions) {
cb();
}
}

private:
CallbackFunction callbackFunction = nullptr;
std::vector<CallbackFunction> callbackFunctions;
};


Expand Down
3 changes: 0 additions & 3 deletions demo_runnable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ int main( int, const char**) {
// do nothing and keep sleeping for 2 secs
std::this_thread::sleep_for(std::chrono::seconds(2));

demoTimer1.unregisterEventRunnable();
demoTimer1.stop();

demoTimer2.unregisterEventRunnable();
demoTimer2.stop();

printf("\n");
Expand Down

0 comments on commit a4d1f20

Please sign in to comment.