|
| 1 | +/** @file |
| 2 | + * |
| 3 | + * @brief Example code demonstrating use of @c chops::wait_queue. |
| 4 | + * See @c threaded_wait_shared_demo.cpp for multithreaded example. |
| 5 | + * |
| 6 | + * @ingroup example_module |
| 7 | + * |
| 8 | + * @author Thurman Gillespy |
| 9 | + * |
| 10 | + * Copyright (c)2019 by Thurman Gillespy |
| 11 | + * 3/22/19 |
| 12 | + * |
| 13 | + * Distributed under the Boost Software License, Version 1.0. |
| 14 | + * (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 15 | + * |
| 16 | + * Sample make file: |
| 17 | + * g++ -std=c++17 -I ~/Projects/utility-rack/include/ wait_queue_demo.cpp |
| 18 | + * |
| 19 | + */ |
| 20 | + |
| 21 | +#include <iostream> |
| 22 | +#include <cstdlib> // EXIT_SUCCESS |
| 23 | +#include <string> |
| 24 | +#include <optional> // std::optional |
| 25 | + |
| 26 | +#include "queue/wait_queue.hpp" |
| 27 | + |
| 28 | +// print queue stats |
| 29 | +void queueState(const chops::wait_queue<int>& wq) { |
| 30 | + |
| 31 | + std::cout << "wait queue contains " << wq.size() << " elements" << std::endl; |
| 32 | + std::cout << "wait queue is empty: " << (wq.empty() ? "true" : "false") << std::endl; |
| 33 | + std::cout << "wait queue is open: " << (wq.is_closed() ? "false" : "true") << std::endl; |
| 34 | + std::cout << std::endl; |
| 35 | +} |
| 36 | + |
| 37 | +// tasty lambda utilities |
| 38 | +constexpr auto printStr = [] (const std::string& s) { std::cout << s << std::endl; }; |
| 39 | +constexpr auto printLn = [] () { std::cout << std::endl; }; |
| 40 | + |
| 41 | +int main() { |
| 42 | + |
| 43 | + // create a new (empty) queue |
| 44 | + printStr("create new wait queue"); |
| 45 | + printLn(); |
| 46 | + chops::wait_queue<int> wq; |
| 47 | + queueState(wq); |
| 48 | + |
| 49 | + // put some values in the queue |
| 50 | + printStr("pushing elements onto the queue..."); |
| 51 | + wq.push(42); wq.push(22); wq.push(102); wq.push(-12); wq.push(17); |
| 52 | + queueState(wq); |
| 53 | + |
| 54 | + // print all the values |
| 55 | + printStr("print all the values in queue"); |
| 56 | + wq.apply([] (int elem) { std::cout << elem << " "; }); |
| 57 | + printLn(); |
| 58 | + |
| 59 | + // remove the elements |
| 60 | + printStr("pop (and remove) each element from the queue"); |
| 61 | + auto num_elements = wq.size(); |
| 62 | + while (num_elements-- > 0) { |
| 63 | + auto result = wq.try_pop(); // std::optional<int> |
| 64 | + if (result) { |
| 65 | + std::cout << result.value() << " "; |
| 66 | + } |
| 67 | + } |
| 68 | + printLn(); |
| 69 | + |
| 70 | + // all done, close shop |
| 71 | + wq.close(); |
| 72 | + queueState(wq); |
| 73 | + |
| 74 | + return EXIT_SUCCESS; |
| 75 | +} |
0 commit comments