Skip to content

Instantly share code, notes, and snippets.

@momchil-velikov
Created November 8, 2015 09:48
Show Gist options
  • Save momchil-velikov/2faeeda3df158a62f3cf to your computer and use it in GitHub Desktop.
Save momchil-velikov/2faeeda3df158a62f3cf to your computer and use it in GitHub Desktop.
#include <iostream>
#include <thread>
#include <deque>
#include <mutex>
#include <condition_variable>
struct queue {
void put(int x) {
std::unique_lock<std::mutex> guard(lock);
q.push_back(x);
if (sleepers && q.size() == 1)
cond.notify_one();
}
int get() {
std::unique_lock<std::mutex> guard(lock);
while (q.size() == 0) {
++sleepers;
cond.wait(guard);
--sleepers;
}
auto x = q.front();
q.pop_front();
return x;
}
unsigned sleepers = 0;
std::deque<int> q;
std::mutex lock;
std::condition_variable cond;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment