Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // double_buffer.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <iostream>
- #include <boost/thread/condition.hpp>
- #include <boost/thread/mutex.hpp>
- #include <boost/thread/thread.hpp>
- #include "binary_semaphore.hpp"
- const int limit = 10;
- typedef boost::mutex::scoped_lock lock;
- typedef std::vector< int > buffer_t;
- // two buffer from which either a producer or consumer will work on
- buffer_t buffer1;
- buffer_t buffer2;
- buffer_t* producer = &buffer1;
- buffer_t* consumer = &buffer2;
- int num_produced_items = 0;
- int num_consumed_items = 0;
- // we need two semaphores to block and unblock both threads appropriately
- binary_semaphore buffer_empty( true ), buffer_ready( false );
- // there are three threads in total to allow the user to exit the program just by hitting a key.
- boost::mutex stop_guard;
- bool stop = false;
- bool finish() { lock lk(stop_guard); return stop; }
- void set_stop() { lock lk(stop_guard); stop = true; }
- void produce()
- {
- while( true )
- {
- // simulate producing
- boost::this_thread::sleep( boost::posix_time::millisec( 500 ));
- producer->push_back( 0 );
- std::cout << "producing from "
- << (( producer == &buffer1 ) ? "1" : "2" )
- << " : " << producer->size()
- << std::endl;
- ++num_produced_items;
- if( producer->size() == limit || finish() == true )
- {
- buffer_empty.wait();
- // swap pointers
- buffer_t* temp = producer;
- producer = consumer;
- consumer = temp;
- buffer_ready.signal();
- }
- if( finish() == true )
- {
- break;
- }
- }
- }
- void consume()
- {
- bool exit = false;
- while( exit == false )
- {
- buffer_ready.wait();
- // simulate consuming
- std::size_t num = consumer->size();
- if( num < limit )
- {
- exit = true;
- }
- for( std::size_t i = 0; i < num; ++i )
- {
- int item = consumer->back();
- consumer->pop_back();
- boost::this_thread::sleep( boost::posix_time::millisec( 1500 ));
- std::cout << "consuming from "
- << (( consumer == &buffer1 ) ? "1" : "2" )
- << ": "
- << consumer->size()
- << std::endl;
- ++num_consumed_items;
- }
- buffer_empty.signal();
- }
- }
- int main( int argc, char* argv[] )
- {
- buffer1.reserve( limit );
- buffer2.reserve( limit );
- boost::thread thrd1( &produce );
- boost::thread thrd2( &consume );
- std::cout << "Press any key to finish program..." << std::endl;
- getchar();
- set_stop();
- thrd1.join();
- thrd2.join();
- std::cout << "produced items: " << num_produced_items << std::endl;
- std::cout << "consumed items: " << num_consumed_items << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement