Skip to content

Instantly share code, notes, and snippets.

@rob-p
Created January 8, 2019 03:52
Show Gist options
  • Save rob-p/ae4b8eb3592496b6fe0aade4a3d6c3a9 to your computer and use it in GitHub Desktop.
Save rob-p/ae4b8eb3592496b6fe0aade4a3d6c3a9 to your computer and use it in GitHub Desktop.
custom queue block size
#include "concurrentqueue.h"
//#include "blockingconcurrentqueue.h"
#include <thread>
#include <atomic>
#include <vector>
#include <iostream>
using namespace moodycamel ;
using namespace std ;
struct MyTraits : public moodycamel::ConcurrentQueueDefaultTraits
{
static const size_t BLOCK_SIZE = 2; // Use bigger blocks
};
int main(){
constexpr int num_producer = 10;
constexpr int num_consumer = 1;
ConcurrentQueue<int, MyTraits> q(1,0,num_producer);
//moodycamel::ProducerToken getProducerToken_();
//moodycamel::ConsumerToken getConsumerToken_();
//BlockingConcurrentQueue<int> q;
int dequeued[num_producer] = { 0 };
std::vector<std::thread> threads; threads.reserve(num_producer+1);
std::atomic<uint32_t> threadsDone{0} ;
using namespace std::chrono_literals;
//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 << "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