// Copyright (c) 2007 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt #include "fork.hpp" #include #include class pooled_executor { private: pooled_executor( pooled_executor const & ); pooled_executor & operator=( pooled_executor const & ); std::list< boost::function< void() > > queue_; std::mutex mtx_; std::condition cnd_; std::vector< std::thread::handle > pool_; public: void thread_proc() { for( ;; ) { std::scoped_lock lock( mtx_ ); while( queue_.empty() ) { cnd_.wait( lock ); } boost::function< void() > fn = queue_.front(); queue_.pop_front(); lock.unlock(); fn(); } } explicit pooled_executor( int n ) { for( int i = 0; i < n; ++i ) { pool_.push_back( std::thread::create( &pooled_executor::thread_proc, this ) ); } } void execute( boost::function< void() > const & fn ) { std::scoped_lock lock( mtx_ ); queue_.push_back( fn ); cnd_.signal(); } }; static pooled_executor s_executor( 4 ); // thread::concurrency() // Fork in thread pool: void fork_impl( boost::function< void() > const & fn ) { s_executor.execute( fn ); } /* // Thread per fork: void fork_impl( boost::function< void() > const & fn ) { thread::create( fn ); } */