Cambridge SMT System
multithreading.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use these files except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 // Copyright 2012 - Gonzalo Iglesias, AdriĆ  de Gispert, William Byrne
14 
15 #ifndef MULTITHREADING_HPP
16 #define MULTITHREADING_HPP
17 
24 namespace ucam {
25 namespace util {
34 
35  private:
36  boost::thread_group pool_;
37  boost::asio::io_service service_;
38  boost::scoped_ptr<boost::asio::io_service::work> work_;
39  std::size_t numthreads_;
40 
41  public:
42  TrivialThreadPool ( std::size_t n )
43  : numthreads_( n > boost::thread::hardware_concurrency()
44  ? boost::thread::hardware_concurrency() : n )
45  , service_ ( numthreads_ )
46  , work_ ( new boost::asio::io_service::work ( service_ ) )
47  {
48  USER_CHECK ( numthreads_ > 0
49  , "Number of threads has to be greater than 0!" );
50  for ( std::size_t i = 0; i < numthreads_; i++ )
51  pool_.create_thread ( boost::bind ( &boost::asio::io_service::run,
52  &service_ ) );
53  }
54 
56  work_.reset();
57  pool_.join_all();
58  }
59 
60  template<typename F>
61  void operator() ( F task ) {
62  service_.post ( task );
63  }
64 
65 };
66 
72  struct NoThreadPool {
73  template<typename F>
74  void operator() (F &task) {
75  task();
76  }
77 };
78 
79 
80 }
81 } // end namespaces
82 
83 #endif
void run(ucam::util::RegistryPO const &rg)
double F
Trivial implementation of a threadpool based on boost::asio methods When initiated, creates a threadpool of n threads (n <= number of cpus). Jobs should be submitted with the templated operator(). When the object is deleted it will wait for all threads to finish.
Trivial struct that can replace seamlessly the threadpool for single threaded executions.
#define USER_CHECK(exp, comment)
Tests whether exp is true. If not, comment is printed and program ends.
Definition: bleu.hpp:14