Skip to content

Instantly share code, notes, and snippets.

@heatblazer
Last active November 2, 2018 14:55
Show Gist options
  • Save heatblazer/fa18b17599096584b154d099550e5966 to your computer and use it in GitHub Desktop.
Save heatblazer/fa18b17599096584b154d099550e5966 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <setjmp.h>
#include <thread>
#define Yield
struct Stack
{
protected:
struct Node
{
int data;
struct Node* next;
Node(int d) : data(d), next(nullptr) {}
};
Node* m_head, *m_tail;
size_t elements; // info
void cleanup()
{
while (m_head)
{
Node* it = m_head;
m_head = m_head->next;
delete it;
}
}
public:
Stack() : m_head(nullptr), m_tail(nullptr), elements(0) {}
virtual ~Stack()
{
cleanup();
}
void push(int i)
{
elements++;
Node* n = new Node(i);
n->next = m_head;
m_head = m_tail = n;
}
int pop()
{
elements--;
Node* n = m_head;
m_head = m_head->next;
int i = n->data;
delete n;
return i;
}
bool empty()
{
return m_head == nullptr;
}
int peek() const
{
if (m_head)
return m_head->data;
return (int)ULONG_MAX;
}
size_t count() { return elements; }
};
struct Queue : public Stack
{
Queue() : Stack() {}
~Queue()
{
Stack::cleanup();
m_tail = nullptr;
}
void append(int i)
{
elements++;
Node* n = new Node(i);
if (m_head == nullptr)
{
n->next = m_head;
m_head = m_tail = n;
}
else
{
m_tail->next = n;
m_tail = n;
}
}
};
static Stack stk;
static jmp_buf cons;
static jmp_buf prod;
[[ noreturn ]] void produce();
void consume();
int main()
{
// produce();
{
Queue q;
for(int i=0; i < 10; ++i)
q.append(i);
while (!q.empty())
std::cout << q.pop() << "\r\n";
}
}
void produce()
{
std::cout << "Producer\r\n";
static int cnt = 0;
int s = setjmp(prod);
for(;;)
{
stk.push(cnt++);
std::cout << "Stack size: (" << stk.count() << ")\r\n";
// longjmp(cons, 1);
consume();
}
}
void consume()
{
std::cout << "Consumer\r\n";
int r;
r = setjmp(cons);
if (r==0)
{
while (!stk.empty())
{
int t = stk.pop();
std::cout << "[" << t << "]";
}
std::cout << "Stack size: (" << stk.count() << ")\r\n";
longjmp(prod, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment