http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue
#include "mpmc.hpp"
using namespace std ;
mpmc_bounded_queue<string> mq(1024) ;
vector<string> vs ;
std::mutex m ;
atomic<int> ipushokcnt ;
void producer(int iThread)
{
for(int idx=0;idx<30000;idx++)
{
int iy ;
if(iThread==3)
iy = idx + 2000000 ;
else if(iThread==2)
iy = idx + 1000000 ;
else
iy = idx ;
string s = to_string(iy);
if(mq.enqueue(s))
{
++ipushokcnt;
//cout << "push is fine" << s << endl ;
}
}
}
void consumer()
{
string strx ;
for(int idx=0;idx<100000000;idx++)
{
if(mq.dequeue(strx))
{
std::unique_lock<std::mutex> guard(m);
vs.push_back(strx) ;
}else{
;
//cout << "pop is false" << endl ;
}
}
}
int main()
{
thread p1(producer,1) ;
thread p2(producer,2) ;
thread p3(producer,3) ;
thread c1(consumer) ;
thread c2(consumer) ;
thread c3(consumer) ;
p1.join() ;
p2.join() ;
p3.join() ;
c1.join() ;
c2.join() ;
c3.join() ;
int icnt = 0 ;
for(const auto i :vs)
{
cout << "(" << i << ")" << endl ;
++icnt ;
}
cout << "ipushokcnt=" << ipushokcnt << ",icnt=" << icnt << endl ;
/*
mq.enqueue("11111") ;
mq.enqueue("33333") ;
mq.enqueue("55555") ;
mq.enqueue("77777") ;
mq.enqueue("99999") ;
string s ;
for(int idx=0;idx<10;idx++)
{
if(mq.dequeue(s))
cout << "True:" << s << endl ;
else
cout << "False" << endl ;
}
*/
}
留言列表