学习笔记:boost spsc队列

#include 
#include 
#include 
#include 
#include 
#include 

class Consumer
{
public:

    struct Data{ int a,b,c; };

	Consumer():stoped_(false),counter_(0){}

	~Consumer(){
	    stop();
	}

	void start(){
		trd_.reset(new boost::thread( boost::bind(&Consumer::run, this)));
	}

	void stop(){
	    stoped_=true;
		trd_->join();
		std::cout << "TOTAL CONSUME "<< counter_ << std::endl;
	}

	bool push(Data& d){
	    return spsc_queue_.push(d);
	}

private:

	void deal(Data& d){
	    counter_+=d.c;
	}
	
	void run(){
		while (!stoped_) {
			if ( 0==spsc_queue_.consume_all( boost::bind(&Consumer::deal,this,_1)))
				boost::this_thread::sleep(boost::posix_time::seconds(0));
        }
        spsc_queue_.consume_all( boost::bind(&Consumer::deal,this,_1));
	}

private:
    boost::lockfree::spsc_queue , 
		                        boost::lockfree::fixed_sized > spsc_queue_;

	bool stoped_;
	boost::shared_ptr trd_;
	int counter_;
};

int main(int argc, char* argv[])
{
	Consumer consumer;
    consumer.start();
	
	Consumer::Data d;
	d.c=1;

	for (int i = 0; i!=10000000; ++i) {

		while (!consumer.push(d)){
		    boost::this_thread::sleep(boost::posix_time::seconds(0));
		}
    }
	
	return 0;
}

你可能感兴趣的:(学习笔记:boost spsc队列)