Language
Compiler
Options
///
/// \file main.cpp
/// \author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja)
/// \edited n/a
/// \created 2017-10-06
/// \last-modified 2017-10-06
/// \brief Actor example.
/// \details
///
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include "ThreadSafeQueue.hpp"
using namespace mn::CppUtils;
struct Cmd {
std::string name;
std::shared_ptr<void> data;
};
// We require a thread-safe queue, which is not part of the standard!
// See https://github.com/mbedded-ninja/CppUtils/blob/master/include/CppUtils/ThreadSafeQueue.hpp
ThreadSafeQueue<Cmd> queue_;
void ThreadFn() {
Cmd cmd;
while(true) {
queue_.Pop(cmd);
std::cout << "Received command. cmd.name = " << cmd.name << std::endl;
///
/// \file ThreadSafeQueue.hpp
/// \author Geoffrey Hunter (www.mbedded.ninja) <gbmhunter@gmail.com>
/// \edited n/a
/// \created 2017-08-09
/// \last-modified 2017-10-06
/// \brief Contains the ThreadSafeQueue class.
/// \details
/// See README.md in root dir for more info.
#ifndef MN_CPP_UTILS_THREAD_SAFE_QUEUE_H_
#define MN_CPP_UTILS_THREAD_SAFE_QUEUE_H_
// System includes
#include <queue>
#include <mutex>
#include <condition_variable>
namespace mn {
namespace CppUtils {
/// \brief A thread-safe queue designed for inter-thread communication.
template<typename T>
class ThreadSafeQueue {
public:
/// \brief Adds something to the back of the thread-safe queue.
/// \details This may be called from multiple threads at the "same time". Method
/// will block until item can be placed onto queue.
void Push(const T &item) {
std::unique_lock<std::mutex> uniqueLock(mutex_);
// Push item onto queue
queue_.push(item);
// IMPORTANT: This has to be done BEFORE conditional variable is notified
$
Received command. cmd.name = CMD_1
Received data (as string) = "hello"
Received command. cmd.name = QUIT
Exit Code:
0