Skip to content

Commit a4d1f20

Browse files
committed
Changed it to vectors of callbacks
1 parent f313ff9 commit a4d1f20

File tree

3 files changed

+21
-27
lines changed

3 files changed

+21
-27
lines changed

CppTimerCallback.h

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,31 @@
33
#include <stdio.h>
44
#include "CppTimer.h"
55
#include <unistd.h>
6+
#include <vector>
67

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

1011
class CppTimerCallback : public CppTimer {
11-
12+
1213
public:
13-
class Runnable {
14-
public:
15-
virtual void run() = 0;
16-
};
17-
18-
void registerEventRunnable(Runnable &h) {
19-
cppTimerEventRunnable = &h;
20-
}
21-
22-
void unregisterEventRunnable() {
23-
cppTimerEventRunnable = NULL;
24-
}
25-
26-
void timerEvent() {
27-
if (cppTimerEventRunnable) {
28-
cppTimerEventRunnable->run();
29-
}
14+
class Runnable {
15+
public:
16+
virtual void run() = 0;
17+
};
18+
19+
void registerEventRunnable(Runnable &h) {
20+
cppTimerEventRunnables.push_back(&h);
21+
}
22+
23+
void timerEvent() {
24+
for(auto & r : cppTimerEventRunnables) {
25+
r->run();
3026
}
27+
}
3128

3229
private:
33-
Runnable* cppTimerEventRunnable = NULL;
34-
30+
std::vector<Runnable*> cppTimerEventRunnables;
3531
};
3632

3733

CppTimerStdFuncCallback.h

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include "CppTimer.h"
55
#include <unistd.h>
66
#include <functional>
7+
#include <vector>
78

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

1718
void registerEventCallback(CallbackFunction cf) {
18-
callbackFunction = cf;
19+
callbackFunctions.push_back(cf);
1920
}
2021

2122
void timerEvent() {
22-
if (nullptr != callbackFunction) {
23-
callbackFunction();
23+
for(auto &cb : callbackFunctions) {
24+
cb();
2425
}
2526
}
2627

2728
private:
28-
CallbackFunction callbackFunction = nullptr;
29+
std::vector<CallbackFunction> callbackFunctions;
2930
};
3031

3132

demo_runnable.cpp

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,7 @@ int main( int, const char**) {
3232
// do nothing and keep sleeping for 2 secs
3333
std::this_thread::sleep_for(std::chrono::seconds(2));
3434

35-
demoTimer1.unregisterEventRunnable();
3635
demoTimer1.stop();
37-
38-
demoTimer2.unregisterEventRunnable();
3936
demoTimer2.stop();
4037

4138
printf("\n");

0 commit comments

Comments
 (0)