2019-09-20 20:58:12 +00:00
|
|
|
#include <assert.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
2023-03-25 21:14:34 +00:00
|
|
|
#include "../public/common/TracySystem.hpp"
|
2019-09-20 20:58:12 +00:00
|
|
|
#include "TracyTaskDispatch.hpp"
|
|
|
|
|
|
|
|
namespace tracy
|
|
|
|
{
|
|
|
|
|
2023-03-25 21:14:34 +00:00
|
|
|
TaskDispatch::TaskDispatch( size_t workers, const char* name )
|
2019-09-20 20:58:12 +00:00
|
|
|
: m_exit( false )
|
|
|
|
, m_jobs( 0 )
|
|
|
|
{
|
|
|
|
assert( workers >= 1 );
|
|
|
|
|
|
|
|
m_workers.reserve( workers );
|
|
|
|
for( size_t i=0; i<workers; i++ )
|
|
|
|
{
|
2023-03-25 21:14:34 +00:00
|
|
|
m_workers.emplace_back( std::thread( [this, name, i]{ SetName( name, i ); Worker(); } ) );
|
2019-09-20 20:58:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
TaskDispatch::~TaskDispatch()
|
|
|
|
{
|
|
|
|
m_exit.store( true, std::memory_order_release );
|
|
|
|
m_queueLock.lock();
|
|
|
|
m_cvWork.notify_all();
|
|
|
|
m_queueLock.unlock();
|
|
|
|
|
|
|
|
for( auto& worker : m_workers )
|
|
|
|
{
|
|
|
|
worker.join();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void TaskDispatch::Queue( const std::function<void(void)>& f )
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock( m_queueLock );
|
|
|
|
m_queue.emplace_back( f );
|
|
|
|
m_cvWork.notify_one();
|
|
|
|
}
|
|
|
|
|
|
|
|
void TaskDispatch::Queue( std::function<void(void)>&& f )
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock( m_queueLock );
|
|
|
|
m_queue.emplace_back( std::move( f ) );
|
|
|
|
m_cvWork.notify_one();
|
|
|
|
}
|
|
|
|
|
|
|
|
void TaskDispatch::Sync()
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> lock( m_queueLock );
|
|
|
|
while( !m_queue.empty() )
|
|
|
|
{
|
|
|
|
auto f = m_queue.back();
|
|
|
|
m_queue.pop_back();
|
|
|
|
lock.unlock();
|
|
|
|
f();
|
|
|
|
lock.lock();
|
|
|
|
}
|
|
|
|
m_cvJobs.wait( lock, [this]{ return m_jobs == 0; } );
|
|
|
|
}
|
|
|
|
|
|
|
|
void TaskDispatch::Worker()
|
|
|
|
{
|
|
|
|
for(;;)
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> lock( m_queueLock );
|
|
|
|
m_cvWork.wait( lock, [this]{ return !m_queue.empty() || m_exit.load( std::memory_order_acquire ); } );
|
|
|
|
if( m_exit.load( std::memory_order_acquire ) ) return;
|
|
|
|
auto f = m_queue.back();
|
|
|
|
m_queue.pop_back();
|
|
|
|
m_jobs++;
|
|
|
|
lock.unlock();
|
|
|
|
f();
|
|
|
|
lock.lock();
|
|
|
|
m_jobs--;
|
|
|
|
if( m_jobs == 0 && m_queue.empty() ) m_cvJobs.notify_one();
|
|
|
|
lock.unlock();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-25 21:14:34 +00:00
|
|
|
void TaskDispatch::SetName( const char* name, size_t num )
|
|
|
|
{
|
|
|
|
char tmp[128];
|
|
|
|
snprintf( tmp, sizeof( tmp ), "%s #%zu", name, num );
|
|
|
|
SetThreadName( tmp );
|
|
|
|
}
|
|
|
|
|
2019-09-20 20:58:12 +00:00
|
|
|
}
|