Skip to content

Instantly share code, notes, and snippets.

@hiraksarkar
Last active January 8, 2019 03:18
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 hiraksarkar/dfeb79dffa549a512dcd3f91f2cff36a to your computer and use it in GitHub Desktop.
Save hiraksarkar/dfeb79dffa549a512dcd3f91f2cff36a to your computer and use it in GitHub Desktop.
#include "concurrentqueue.h"
#include "blockingconcurrentqueue.h"
#include <thread>
#include <atomic>
#include <vector>
#include <iostream>
using namespace moodycamel ;
using namespace std ;
int main(){
constexpr int num_producer = 10;
constexpr int num_consumer = 1;
ConcurrentQueue<int> q(0,0,1);
moodycamel::ProducerToken getProducerToken_();
moodycamel::ConsumerToken getConsumerToken_();
//BlockingConcurrentQueue<int> q;
int dequeued[num_producer*10] = { 0 };
std::vector<std::thread> threads; threads.reserve(num_producer+1);
std::atomic<uint32_t> threadsDone{0} ;
//Consumers
//for (int i = 5 ; i != 10; ++i) {
threads.push_back(std::thread([&]() {
while(threadsDone < 10){
int item;
while(q.try_dequeue(item)) {
//std::cout << "dequeud " << item << "\n\n" ;
std::cout << "threadsDone: " << threadsDone << "\n" ;
++dequeued[item];
}
//std::cout << "q.size_approx() " << q.size_approx() << "\n " ;
}
}));
// Producers
for (int i = 0; i != 10; ++i) {
threads.push_back(std::thread([&, i]() {
std::cout << "debug\n" ;
for(int j = 0; j < 10 ; ++j){
while(!q.try_enqueue(i)) {
std::cout << "q.size_approx() " << q.size_approx() << ", trying to enqueue from thread " << i << "\n " ;
//std::cout << "in try_enq\n\n" ;
}
std::cout << "Done\n" ;
}
threadsDone++ ;
}));
}
//}
// Wait for all threads
for (auto& t : threads) {
t.join();
}
// Collect any leftovers (could be some if e.g. consumers finish before producers)
int item;
while (q.try_dequeue(item)) {
++dequeued[item];
}
return 0 ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment