Last active
December 28, 2015 19:18
-
-
Save argv0/7548792 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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