Skip to content

Instantly share code, notes, and snippets.

@owlfox
Created February 13, 2020 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owlfox/f658296067d784ea24b477248190d80a to your computer and use it in GitHub Desktop.
Save owlfox/f658296067d784ea24b477248190d80a to your computer and use it in GitHub Desktop.
consumer, producer(?)
#include <chrono>
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
const int N{8};
static int fifo[N];
volatile static unsigned int head{0}, tail{0}; // init empty
static int count{0};
void consumer() {
while (true) {
while (head == tail) {
std::cout << "empty!\n";
std::this_thread::sleep_for(0.5s);
}
auto new_head = head + 1;
if (new_head >= N)
new_head = 0;
std::cout << "consumed: " << fifo[head] << '\n';
head = new_head;
std::this_thread::sleep_for(2s);
}
}
void producer() {
while (true) {
auto new_tail = tail + 1;
if (new_tail >= N) {
new_tail = 0;
};
while (new_tail == head) {
std::cout << "full!\n";
std::this_thread::sleep_for(0.5s);
}
fifo[tail] = count;
std::cout << "produced: " << fifo[tail] << '\n';
count += 1;
tail = new_tail;
std::this_thread::sleep_for(1s);
}
}
int protected_main(int argc, char** argv) {
std::thread t1{producer};
std::thread t2{consumer};
t1.join();
t2.join();
return EXIT_SUCCESS;
}
int main(int argc, char** argv) {
try {
return protected_main(argc, argv);
} catch (const std::exception& e) {
std::cerr << "Caught unhandled exception:\n";
std::cerr << " - what(): " << e.what() << '\n';
} catch (...) {
std::cerr << "Caught unknown exception\n";
}
return EXIT_FAILURE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment