Skip to content

Instantly share code, notes, and snippets.

@argv0
Last active December 28, 2015 19:18
Show Gist options
  • Save argv0/7548792 to your computer and use it in GitHub Desktop.
Save argv0/7548792 to your computer and use it in GitHub Desktop.
#include <mutex>
#include <thread>
#include <async>
using namespace std;
template <typename T>
struct locked_queue
{
typedef lock_guard<mutex> lock_guard;
locked_queue(size_t size)
: size_(size) {}
void produce(const T& item)
{
lock_guard lock(mtx_);
q_.push(item);
}
void consume(T& item)
{
lock_guard lock(mtx_);
item = q_.front();
q_.pop();
}
private:
queue<T> q_;
mutable mutex mtx_;
size_t size_;
};
typedef lockfree_queue<int> lockfree_int_queue;
typedef locked_queue<int> locked_int_queue;
int main(void)
{
lockfree_int_queue q(10000000);
auto producer = [&q](size_t count) {
for (int i=0; i < count ; i++)
q.produce(i);
};
auto consumer = [&q](size_t count) {
for (int i=0; i < count; i++) {
int result;
q.consume(result);
}
};
async(producer, 1000000).get();
auto p = async(producer, 1000000);
auto c = async(consumer, 1000000);
p.get();
c.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment