Commit ebd8d90fc01e1d5be2c12f8e42921f3f5f9b12ae
1 parent
eefcc060
Added FIFO example
Showing
2 changed files
with
54 additions
and
0 deletions
examples09/07-fifo/fifo.cpp
0 → 100644
| 1 | +#include <deque> | ||
| 2 | +#include <list> | ||
| 3 | +#include <iostream> | ||
| 4 | +#include <thread> | ||
| 5 | +#include <mutex> | ||
| 6 | +#include <unistd.h> | ||
| 7 | +#include <condition_variable> | ||
| 8 | +#include <chrono> | ||
| 9 | + | ||
| 10 | +using namespace std; | ||
| 11 | + | ||
| 12 | +std::deque<unsigned int> FIFO; | ||
| 13 | +std::mutex FIFO_lock; | ||
| 14 | +std::condition_variable cv; | ||
| 15 | + | ||
| 16 | +void process() | ||
| 17 | +{ | ||
| 18 | + while(1) | ||
| 19 | + { | ||
| 20 | + std::unique_lock l(FIFO_lock); | ||
| 21 | + cv.wait(l, [] {return !FIFO.empty();}); | ||
| 22 | + { | ||
| 23 | + do { | ||
| 24 | + cout << FIFO.back() << endl; | ||
| 25 | + FIFO.pop_back(); | ||
| 26 | + } while (!FIFO.empty()); | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +int main() | ||
| 32 | +{ | ||
| 33 | + std::thread t(process); | ||
| 34 | + unsigned int i = 0; | ||
| 35 | + while(1) | ||
| 36 | + { | ||
| 37 | + { | ||
| 38 | + std::unique_lock l(FIFO_lock); | ||
| 39 | + FIFO.push_front(i++); | ||
| 40 | + } | ||
| 41 | + cv.notify_one(); | ||
| 42 | + std::this_thread::sleep_for(10ms); | ||
| 43 | + } | ||
| 44 | +} |