00001 #include "ros1_cpptemplate/atomic_fibonacci.hpp" 00002 00003 #include <ros/console.h> 00004 #include <iostream> 00005 #include <sstream> 00006 #include <string> 00007 00008 namespace ros1_cpptemplate 00009 { 00010 00011 AtomicFibonacci::AtomicFibonacci(const int& last_number, const int& current_number, const int& max_number, 00012 const std::string& name) 00013 { 00014 last_number_ = last_number; 00015 current_number_ = current_number; 00016 max_number_ = max_number; 00017 00018 if (name == "") 00019 { 00020 // don't show empty [] brackets 00021 log_prefix_ = ""; 00022 } 00023 else 00024 { 00025 std::stringstream log_prefix_string_stream; 00026 log_prefix_string_stream << "[" << name << "] "; 00027 log_prefix_ = log_prefix_string_stream.str(); 00028 } 00029 } 00030 00031 AtomicFibonacci::~AtomicFibonacci() 00032 { 00033 } 00034 00035 int AtomicFibonacci::nextAndLog(const std::string& log_prefix) 00036 { 00037 std::lock_guard<std::mutex> lock(mutex_); 00038 int next_number = next_(); 00039 ROS_INFO_STREAM(log_prefix_ << log_prefix << "Next fibonacci_number: " << next_number); 00040 return next_number; 00041 } 00042 00043 int AtomicFibonacci::next() 00044 { 00045 std::lock_guard<std::mutex> lock(mutex_); 00046 return next_(); 00047 } 00048 00049 int AtomicFibonacci::nextNext() 00050 { 00051 std::lock_guard<std::mutex> lock(mutex_); 00052 next_(); 00053 return next_(); 00054 } 00055 00056 int AtomicFibonacci::next_() 00057 { 00058 int new_number = current_number_ + last_number_; 00059 last_number_ = current_number_; 00060 00061 if (new_number > max_number_) 00062 { 00063 // wrap around to avoid overflow 00064 new_number = 1; 00065 last_number_ = 0; 00066 } 00067 00068 current_number_ = new_number; 00069 00070 return new_number; 00071 } 00072 00073 void AtomicFibonacci::setMax(const int& value) 00074 { 00075 max_number_ = value; 00076 } 00077 00078 } // namespace