Skip to content

Commit

Permalink
Channel structure has been completed
Browse files Browse the repository at this point in the history
  • Loading branch information
leventkaragol committed May 22, 2024
1 parent 81af030 commit 9409079
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/libcpp-channel.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,15 @@ SOFTWARE.
#include <condition_variable>
#include <optional>
#include <memory>
#include <vector>
#include <unordered_map>

namespace lklibs
{
/**
* @brief Thread-safe generic message channel
*
* @tparam T
*/
template <typename T>
class Channel
{
Expand All @@ -61,13 +65,22 @@ namespace lklibs
{
}

/**
* @brief Producer class to send messages to the channel
*
*/
class Producer
{
public:
explicit Producer(std::shared_ptr<Data> data) : data_(std::move(data))
{
}

/**
* @brief Send message to the channel
*
* @param value
*/
void send(T value)
{
auto message = std::make_shared<T>(std::move(value));
Expand All @@ -91,6 +104,10 @@ namespace lklibs
std::shared_ptr<Data> data_;
};

/**
* @brief Consumer class to receive messages from the channel
*
*/
class Consumer
{
public:
Expand All @@ -108,6 +125,11 @@ namespace lklibs
data_->consumer_queues_.erase(consumer_id_);
}

/**
* @brief Receive message from the channel
*
* @return std::optional<T>
*/
std::optional<T> receive()
{
std::unique_lock<std::mutex> lock(data_->mutex_);
Expand All @@ -133,11 +155,21 @@ namespace lklibs
int consumer_id_;
};

/**
* @brief Get producer object which can be used to send messages
*
* @return Producer
*/
Producer getProducer()
{
return Producer(data_);
}

/**
* @brief Get consumer object which can be used to receive messages
*
* @return Consumer
*/
Consumer getConsumer()
{
return Consumer(data_);
Expand Down

0 comments on commit 9409079

Please sign in to comment.