Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <chrono>
- #include <thread>
- #include <atomic>
- #include <mutex>
- #include <condition_variable>
- using ClockT = std::chrono::high_resolution_clock;
- ClockT::time_point Start;
- struct ThreadPool
- {
- const std::size_t ThreadCount = std::max< unsigned >( 1, std::thread::hardware_concurrency() );
- std::atomic< std::size_t > Running{ 0 };
- bool Started = false;
- bool Kill = false;
- std::vector< std::thread > Threads;
- std::vector< double > Measurements;
- std::condition_variable Cv;
- std::mutex Mutex;
- struct Worker
- {
- ThreadPool* Pool;
- explicit Worker( ThreadPool* Pool )
- : Pool{ Pool }
- {
- }
- void operator()()
- {
- const auto Check = [ this ]{ return this->Pool->Started || this->Pool->Kill; };
- while( true )
- {
- if( !Check() )
- {
- std::unique_lock< decltype( Pool->Mutex ) > Lock( Pool->Mutex );
- Pool->Cv.wait( Lock, Check );
- }
- if( Pool->Kill )
- {
- return;
- }
- else
- {
- Pool->Measurements[ Pool->Running++ ] = std::chrono::duration_cast< std::chrono::duration< double, std::milli > >( ClockT::now() - Start ).count();
- do
- {
- // Task();
- }
- while( Pool->Started && !Pool->Kill );
- --Pool->Running;
- }
- }
- }
- };
- ThreadPool()
- : Measurements( ThreadCount )
- {
- Threads.reserve( ThreadCount );
- while( Threads.size() < Threads.capacity() )
- {
- Threads.emplace_back( Worker{ this } );
- }
- }
- ~ThreadPool()
- {
- Kill = true;
- Cv.notify_all();
- while( !Threads.empty() )
- {
- Threads.back().join();
- Threads.pop_back();
- }
- }
- void Run()
- {
- Started = true;
- Cv.notify_all();
- std::this_thread::yield();
- }
- };
- int main()
- {
- ThreadPool Tp;
- std::this_thread::sleep_for( std::chrono::milliseconds{ 100 } );
- Start = ClockT::now();
- Tp.Run();
- std::this_thread::sleep_for( std::chrono::milliseconds{ 500 } );
- for( auto const& i : Tp.Measurements )
- {
- std::cout << i << "ms\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment