Skip to content

Commit

Permalink
fix(threading): Lock mutex for each tread pool task.
Browse files Browse the repository at this point in the history
  • Loading branch information
na2axl committed Oct 30, 2024
1 parent 2804e70 commit 850ba2e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
23 changes: 11 additions & 12 deletions src/Core/Thread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -425,17 +425,16 @@ namespace SparkyStudios::Audio::Amplitude::Thread
{
std::shared_ptr<PoolTask> t = nullptr;

if (_workMutex)
LockMutex(_workMutex);

if (_taskCount > 0)
{
AmInt32 r;
AmInt32 c = 0;

do
{
r = _robin % _taskCount;
if (_workMutex)
LockMutex(_workMutex);

AmInt32 r = _robin % _taskCount;
_robin++;
t = _taskArray[r];

Expand All @@ -444,20 +443,20 @@ namespace SparkyStudios::Audio::Amplitude::Thread
_taskArray[r] = _taskArray[_taskCount - 1];
_taskCount--;

if (_workMutex)
UnlockMutex(_workMutex);

break;
}
else
{
t = nullptr;
}

t = nullptr;
c++;

if (_workMutex)
UnlockMutex(_workMutex);
} while (c < _taskCount);
}

if (_workMutex)
UnlockMutex(_workMutex);

return t;
}

Expand Down
6 changes: 3 additions & 3 deletions tests/thread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class DummyPoolTask : public Thread::PoolTask
{
_executingThreadId = Thread::GetCurrentThreadId();
if (_targetThreadId != _executingThreadId)
Thread::Sleep(100);
Thread::Sleep(500);

_isExecuted = true;
}
Expand Down Expand Up @@ -156,7 +156,7 @@ TEST_CASE("Thread Pool Tests", "[thread][amplitude]")

THEN("the task is executed")
{
Thread::Sleep(150); // Wait for the task to execute
Thread::Sleep(550); // Wait for the task to execute
REQUIRE(task->IsExecuted());

AND_THEN("the task is removed from the pool")
Expand All @@ -175,7 +175,7 @@ TEST_CASE("Thread Pool Tests", "[thread][amplitude]")
auto task = std::make_shared<DummyPoolTask>(threadId);
REQUIRE_FALSE(task->IsExecuted());

bool willExecuteWorkInCallerThread = pool.GetTaskCount() > AM_MAX_THREAD_POOL_TASKS;
bool willExecuteWorkInCallerThread = pool.GetTaskCount() >= AM_MAX_THREAD_POOL_TASKS;

pool.AddTask(task);

Expand Down

0 comments on commit 850ba2e

Please sign in to comment.