Skip to content

Commit

Permalink
Fix deadlocks by enabling reuse of exited threads (shadps4-emu#855)
Browse files Browse the repository at this point in the history
Simplify loop

const correctness

Simplify setting is_free

Co-authored-by: Adam Jones <[email protected]>
  • Loading branch information
adjonesey and AdJones authored Sep 9, 2024
1 parent f23c6dc commit dcab06f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
13 changes: 8 additions & 5 deletions src/core/libraries/kernel/thread_management.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,12 @@ void init_pthreads() {
}

void pthreadInitSelfMainThread() {
const char* name = "Main_Thread";
auto* pthread_pool = g_pthread_cxt->GetPthreadPool();
g_pthread_self = pthread_pool->Create();
g_pthread_self = pthread_pool->Create(name);
scePthreadAttrInit(&g_pthread_self->attr);
g_pthread_self->pth = pthread_self();
g_pthread_self->name = "Main_Thread";
g_pthread_self->name = name;
}

int PS4_SYSV_ABI scePthreadAttrInit(ScePthreadAttr* attr) {
Expand Down Expand Up @@ -1016,7 +1017,7 @@ int PS4_SYSV_ABI scePthreadCreate(ScePthread* thread, const ScePthreadAttr* attr
attr = g_pthread_cxt->GetDefaultAttr();
}

*thread = pthread_pool->Create();
*thread = pthread_pool->Create(name);

if ((*thread)->attr != nullptr) {
scePthreadAttrDestroy(&(*thread)->attr);
Expand Down Expand Up @@ -1058,11 +1059,11 @@ int PS4_SYSV_ABI scePthreadCreate(ScePthread* thread, const ScePthreadAttr* attr
}
}

ScePthread PThreadPool::Create() {
ScePthread PThreadPool::Create(const char* name) {
std::scoped_lock lock{m_mutex};

for (auto* p : m_threads) {
if (p->is_free) {
if (p->is_free && p->name == name) {
p->is_free = false;
return p;
}
Expand Down Expand Up @@ -1491,6 +1492,8 @@ int PS4_SYSV_ABI scePthreadOnce(int* once_control, void (*init_routine)(void)) {
}

[[noreturn]] void PS4_SYSV_ABI scePthreadExit(void* value_ptr) {
g_pthread_self->is_free = true;

pthread_exit(value_ptr);
UNREACHABLE();
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/libraries/kernel/thread_management.h
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ struct PthreadSemInternal {

class PThreadPool {
public:
ScePthread Create();
ScePthread Create(const char* name);

private:
std::vector<ScePthread> m_threads;
Expand Down

0 comments on commit dcab06f

Please sign in to comment.