1
0
mirror of https://github.com/RPCS3/rpcs3.git synced 2024-11-25 04:02:42 +01:00
rpcs3/Utilities/Thread.cpp

175 lines
2.5 KiB
C++
Raw Normal View History

#include "stdafx.h"
#include "Utilities/Log.h"
2014-07-11 13:59:13 +02:00
#include "Emu/Memory/Memory.h"
#include "Thread.h"
thread_local NamedThreadBase* g_tls_this_thread = nullptr;
std::atomic<u32> g_thread_count(0);
NamedThreadBase* GetCurrentNamedThread()
{
return g_tls_this_thread;
}
std::string NamedThreadBase::GetThreadName() const
{
return m_name;
}
void NamedThreadBase::SetThreadName(const std::string& name)
{
m_name = name;
}
ThreadBase::ThreadBase(const std::string& name)
: NamedThreadBase(name)
, m_executor(nullptr)
, m_destroy(false)
, m_alive(false)
{
}
ThreadBase::~ThreadBase()
{
if(IsAlive())
Stop(false);
safe_delete(m_executor);
}
void ThreadBase::Start()
{
if(m_executor) Stop();
std::lock_guard<std::mutex> lock(m_main_mutex);
m_destroy = false;
m_alive = true;
m_executor = new std::thread(
[this]()
{
g_tls_this_thread = this;
g_thread_count++;
2014-07-07 19:22:36 +02:00
try
{
Task();
}
catch (const std::string& e)
{
LOG_ERROR(GENERAL, "Exception: %s", e.c_str());
}
catch (const char* e)
{
LOG_ERROR(GENERAL, "Exception: %s", e);
}
catch (int exitcode)
{
LOG_SUCCESS(GENERAL, "Exit Code: %d", exitcode);
}
m_alive = false;
g_thread_count--;
});
}
void ThreadBase::Stop(bool wait, bool send_destroy)
{
std::lock_guard<std::mutex> lock(m_main_mutex);
if (send_destroy)
m_destroy = true;
if(!m_executor)
return;
if(wait && m_executor->joinable() && m_alive)
{
m_executor->join();
}
else
{
m_executor->detach();
}
delete m_executor;
m_executor = nullptr;
}
bool ThreadBase::Join() const
{
std::lock_guard<std::mutex> lock(m_main_mutex);
if(m_executor->joinable() && m_alive && m_executor != nullptr)
{
m_executor->join();
return true;
}
return false;
}
bool ThreadBase::IsAlive() const
{
std::lock_guard<std::mutex> lock(m_main_mutex);
return m_alive;
}
bool ThreadBase::TestDestroy() const
{
return m_destroy;
}
thread::thread(const std::string& name, std::function<void()> func) : m_name(name)
{
start(func);
}
thread::thread(const std::string& name) : m_name(name)
{
}
thread::thread()
{
}
void thread::start(std::function<void()> func)
2014-02-27 19:25:32 +01:00
{
std::string name = m_name;
m_thr = std::thread([func, name]()
2014-02-19 18:27:52 +01:00
{
2014-02-27 19:25:32 +01:00
NamedThreadBase info(name);
g_tls_this_thread = &info;
g_thread_count++;
2014-02-19 18:27:52 +01:00
try
{
func();
}
catch(...)
{
LOG_ERROR(HLE, "Crash :(");
2014-02-27 19:25:32 +01:00
//std::terminate();
2014-02-19 18:27:52 +01:00
}
g_thread_count--;
2014-02-19 18:27:52 +01:00
});
}
void thread::detach()
{
m_thr.detach();
}
void thread::join()
{
m_thr.join();
}
bool thread::joinable() const
{
return m_thr.joinable();
}