Skip to content

Instantly share code, notes, and snippets.

@devendranaga
Created November 4, 2021 12:30
Show Gist options
  • Save devendranaga/c233a436d449a61008eb87ff26005474 to your computer and use it in GitHub Desktop.
Save devendranaga/c233a436d449a61008eb87ff26005474 to your computer and use it in GitHub Desktop.
safe_queue
/**
* @brief - a demo example of Safe Queue
*
* @copyright - 2021-present All rights reserved
*
* @author - Devendra Naga (devendra.aaru@outlook.com)
*
* @license - proprietary license, ask author for more information
*/
#include "safe_queue.h"
/**
* @brief - receive callback for integer data
*
* @param in id - subscriber id
* @param in val - value sent by the publisher
*/
void receive_callback(int id, int val)
{
printf("subscriber[%d] received val %d\n", id, val);
}
/**
* @brief - receive callback for string data
*
* @param in id - subscriber id
* @param in val - val sent by the publisher
*/
void receive_callback_1(int id, std::string val)
{
printf("subscriber_str[%d] received val %s\n", id, val.c_str());
}
/**
* @brief - subscriber
*/
void subscriber()
{
// subscribe to integers - there can be many subscribers for a publisher
Auto_OS::Lib::SafeQueue<int>::Instance()->Subscribe(1, receive_callback);
Auto_OS::Lib::SafeQueue<int>::Instance()->Subscribe(2, receive_callback);
Auto_OS::Lib::SafeQueue<int>::Instance()->Subscribe(3, receive_callback);
Auto_OS::Lib::SafeQueue<int>::Instance()->Subscribe(4, receive_callback);
Auto_OS::Lib::SafeQueue<int>::Instance()->Subscribe(5, receive_callback);
Auto_OS::Lib::SafeQueue<int>::Instance()->Subscribe(0, receive_callback);
// subscribe to strings
Auto_OS::Lib::SafeQueue<std::string>::Instance()->Subscribe(7, receive_callback_1);
Auto_OS::Lib::SafeQueue<std::string>::Instance()->Subscribe(8, receive_callback_1);
}
/**
* @brief - publisher
*/
void publisher()
{
int pub_inc = 0;
std::string msg = "hello";
while (1) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
pub_inc ++;
// queue integer type
Auto_OS::Lib::SafeQueue<int>::Instance()->QueueItem(pub_inc);
// queue string type
Auto_OS::Lib::SafeQueue<std::string>::Instance()->QueueItem(msg);
}
}
int main()
{
std::thread t1(publisher);
std::thread t2(subscriber);
t1.join();
t2.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment