- 论坛徽章:
- 1
|
本帖最后由 lost_templar 于 2014-04-30 21:53 编辑
临时这么办了,虽然粗制滥造,但是总算解决了:
让主线程负责擦屁股。
- struct simple_thread_pool
- {
- typedef std::function<void()> function_type;
- std::atomic_bool all_done_flag;
- std::queue<function_type> work_queue;
- mutable std::mutex work_queue_mutex;
- std::vector<std::thread> thread_array;
- simple_thread_pool( std::size_t max_threads_ = std::thread::hardware_concurrency() ) : all_done_flag{ false }
- {
- if ( !max_threads_ )
- max_threads_ = 2;
- try
- {
- for ( std::size_t index = 0; index != max_threads_; ++index )
- thread_array.push_back( std::thread{ &simple_thread_pool::work_loader, this } );
- }
- catch(...)
- {
- all_done_flag = true;
- throw;
- }
- }
- ~simple_thread_pool()
- {
- while ( true )
- {
- function_type remaining_work = nullptr;
- {
- std::lock_guard<std::mutex> lg{ work_queue_mutex };
- if ( !work_queue.empty() )
- {
- remaining_work = work_queue.front();
- work_queue.pop();
- }
- }
- if ( remaining_work )
- remaining_work();
- else
- break;
- }
- all_done_flag = true;
- std::for_each( thread_array.begin(), thread_array.end(), [](std::thread& the_thread) { if ( the_thread.joinable() ) the_thread.join(); } );
- }
- template< typename Function >
- void submit_work( Function f_ )
- {
- std::lock_guard<std::mutex> lk{ work_queue_mutex };
- work_queue.push( function_type{f_} );
- }
- void work_loader()
- {
- while ( ! all_done_flag )
- {
- function_type current_work = nullptr;
- {
- std::lock_guard<std::mutex> lg{ work_queue_mutex };
- if ( !work_queue.empty() )
- {
- current_work = work_queue.front();
- work_queue.pop();
- }
- }
- if ( !current_work )
- current_work = [](){ std::this_thread::yield(); };
- current_work();
- }
- }
- simple_thread_pool( simple_thread_pool const& ) = delete;
- simple_thread_pool& operator = ( simple_thread_pool const& ) = delete;
- simple_thread_pool( simple_thread_pool && ) = delete;
- simple_thread_pool& operator = ( simple_thread_pool && ) = delete;
- };//struct simple_thead_pool
复制代码 |
|