Skip to content

Commit 7d4cac5

Browse files
canard: implement a lightweight way to share mutex between same message type subscribers
1 parent 50dcf28 commit 7d4cac5

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

canard/subscriber.h

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,17 @@ class Subscriber : public HandlerList {
4141
Subscriber(Callback<msgtype> &_cb, uint8_t _index) :
4242
HandlerList(CanardTransferTypeBroadcast, msgtype::cxx_iface::ID, msgtype::cxx_iface::SIGNATURE, _index),
4343
cb (_cb) {
44+
if (branch_head[index] == nullptr) {
4445
#ifdef CANARD_MUTEX_ENABLED
45-
WITH_SEMAPHORE(sem[index]);
46+
sem = allocate<Canard::Semaphore>(); // allocate a semaphore
47+
#endif
48+
} else {
49+
#ifdef CANARD_MUTEX_ENABLED
50+
sem = branch_head[index]->sem;
51+
#endif
52+
}
53+
#ifdef CANARD_MUTEX_ENABLED
54+
WITH_SEMAPHORE(*sem);
4655
#endif
4756
next = branch_head[index];
4857
branch_head[index] = this;
@@ -53,9 +62,17 @@ class Subscriber : public HandlerList {
5362

5463
// destructor, remove the entry from the singly-linked list
5564
~Subscriber() {
65+
#ifdef CANARD_MUTEX_ENABLED
66+
WITH_SEMAPHORE(*sem);
67+
#endif
5668
Subscriber<msgtype>* entry = branch_head[index];
5769
if (entry == this) {
5870
branch_head[index] = next;
71+
if (branch_head[index] == nullptr) {
72+
#ifdef CANARD_MUTEX_ENABLED
73+
deallocate(sem);
74+
#endif
75+
}
5976
return;
6077
}
6178
while (entry != nullptr) {
@@ -70,6 +87,9 @@ class Subscriber : public HandlerList {
7087
/// @brief parse the message and call the callback
7188
/// @param transfer transfer object
7289
void handle_message(const CanardRxTransfer& transfer) override {
90+
#ifdef CANARD_MUTEX_ENABLED
91+
WITH_SEMAPHORE(*sem);
92+
#endif
7393
msgtype msg {};
7494
msgtype::cxx_iface::decode(&transfer, &msg);
7595
// call all registered callbacks in one go
@@ -84,19 +104,14 @@ class Subscriber : public HandlerList {
84104
Subscriber<msgtype>* next;
85105
static Subscriber<msgtype> *branch_head[CANARD_NUM_HANDLERS];
86106
#ifdef CANARD_MUTEX_ENABLED
87-
static Canard::Semaphore sem[CANARD_NUM_HANDLERS];
107+
Canard::Semaphore *sem;
88108
#endif
89109
Callback<msgtype> &cb;
90110
};
91111

92112
template <typename msgtype>
93113
Subscriber<msgtype>* Subscriber<msgtype>::branch_head[] = {nullptr};
94114

95-
#ifdef CANARD_MUTEX_ENABLED
96-
template <typename msgtype>
97-
Canard::Semaphore Subscriber<msgtype>::sem[CANARD_NUM_HANDLERS];
98-
#endif
99-
100115
template <typename T, typename msgtype>
101116
class SubscriberArgCb {
102117
public:

0 commit comments

Comments
 (0)