xterminhate Si vis pacem, para bellum. | Je tenais à coder ça par moi même, et bien le resultat est pas triste bien sur. Assert dans Boost::mutex.inl. toute suggestion est la bienvenue.
Code :
- template< typename task, typename function >
- struct thread_pool : private boost::noncopyable
- {
- // one thread of the pool
- struct one_thread
- {
- // constructor
- one_thread( bool & r, fifo< task >& f ) : running( r ), task_queue( f ) {};
- // thread function
- void operator()() const
- {
- while( running )
- function()( task_queue.read() );
- }
- private:
- bool& running;
- fifo< task >& task_queue;
- };
- // constructor
- thread_pool( unsigned const & thread_number ) :
- task_queue( thread_number * 2 ),
- running( true )
- {
- // create all the threads of the pool
- for( unsigned index = 0; index != thread_number; ++index )
- tg.create_thread( one_thread( running, task_queue ) );
- }
- // new task
- inline void push_task( task const & t )
- {
- task_queue.write( t );
- }
- // stop
- inline void stop()
- {
- running = false;
- }
- // destructor
- ~thread_pool()
- {
- running = false;
- tg.join_all();
- }
- private:
- // thread group
- thread_group tg;
- // message queue
- fifo< task > task_queue;
- // status
- bool running;
- };
|
Au cas ou, voici le code de la fifo (qui marche parfaitement).
Code :
- template< typename X >
- struct fifo : private boost::noncopyable
- {
- fifo( const int& n ) :
- begin( 0 ),
- end( 0 ),
- buffered( 0 ),
- circular_buf( n )
- {
- }
- void write( const X& m )
- {
- lock lk( monitor );
- while ( buffered == circular_buf.size() )
- buffer_not_full.wait( lk );
- circular_buf[ end ] = m;
- end = ( end + 1 ) % circular_buf.size();
- ++buffered;
- buffer_not_empty.notify_one();
- }
- X read()
- {
- lock lk( monitor );
- while ( buffered == 0 )
- buffer_not_empty.wait( lk );
- X i = circular_buf[ begin ];
- begin = ( begin + 1 ) % circular_buf.size();
- --buffered;
- buffer_not_full.notify_one();
- return i;
- }
- private:
- unsigned int begin, end, buffered;
- vector< X > circular_buf;
- condition buffer_not_full, buffer_not_empty;
- mutex monitor;
- };
|
---------------
Cordialement, Xterm-in'Hate...
|