SMACC2
Loading...
Searching...
No Matches
callback_counter_semaphore.cpp
Go to the documentation of this file.
1// Copyright 2025 Robosoft Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/*****************************************************************************************************************
16 *
17 * Authors: Pablo Inigo Blasco, Brett Aldrich
18 *
19 *****************************************************************************************************************/
20#include <condition_variable>
21#include <iostream>
22#include <mutex>
23#include <rclcpp/rclcpp.hpp>
25#include <thread>
26
27namespace smacc2
28{
30: count_(count), name_(name)
31{
32}
33
35{
36 std::unique_lock<std::mutex> lock(mutex_);
37 RCLCPP_DEBUG(
38 rclcpp::get_logger(name_), "[CallbackCounterSemaphore] acquire callback %s %ld", name_.c_str(),
39 (long)this);
40
41 if (finalized)
42 {
43 RCLCPP_DEBUG(
44 rclcpp::get_logger(name_), "[CallbackCounterSemaphore] callback rejected %s %ld",
45 name_.c_str(), (long)this);
46 return false;
47 }
48
49 ++count_;
50 cv_.notify_one();
51
52 RCLCPP_DEBUG(
53 rclcpp::get_logger(name_), "[CallbackCounterSemaphore] callback accepted %s %ld", name_.c_str(),
54 (long)this);
55 return true;
56}
57
59{
60 std::unique_lock<std::mutex> lock(mutex_);
61 --count_;
62 cv_.notify_one();
63
64 RCLCPP_DEBUG(
65 rclcpp::get_logger(name_), "[CallbackCounterSemaphore] callback finished %s %ld", name_.c_str(),
66 (long)this);
67}
68
70{
71 std::unique_lock<std::mutex> lock(mutex_);
72
73 while (count_ > 0)
74 {
75 cv_.wait(lock);
76 }
77 finalized = true;
78
79 for (auto conn : connections_)
80 {
81 conn.disconnect();
82 }
83
84 connections_.clear();
85 RCLCPP_DEBUG(
86 rclcpp::get_logger(name_), "[CallbackCounterSemaphore] callbacks finalized %s %ld",
87 name_.c_str(), (long)this);
88}
89
91{
92 std::unique_lock<std::mutex> lock(mutex_);
93
94 if (finalized)
95 {
96 RCLCPP_DEBUG(
97 rclcpp::get_logger(name_),
98 "[CallbackCounterSemaphore] ignoring adding callback, already finalized %s %ld",
99 name_.c_str(), (long)this);
100 return;
101 }
102
103 connections_.push_back(conn);
104}
105
106} // namespace smacc2
void addConnection(smacc2::SmaccSignalConnection conn)
CallbackCounterSemaphore(std::string name, int count=0)
std::vector< smacc2::SmaccSignalConnection > connections_
boost::signals2::connection SmaccSignalConnection