Skip to content

Commit

Permalink
fix(worker): task queue should not be blocked when running a task
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-soft committed Mar 4, 2019
1 parent fc54a64 commit 2b41f54
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 13 deletions.
2 changes: 2 additions & 0 deletions include/LCUI/worker.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ LCUI_API LCUI_Worker LCUIWorker_New(void);

LCUI_API void LCUIWorker_PostTask(LCUI_Worker worker, LCUI_Task task);

LCUI_API LCUI_Task LCUIWorker_GetTask(LCUI_Worker worker);

LCUI_API LCUI_BOOL LCUIWorker_RunTask(LCUI_Worker worker);

LCUI_API int LCUIWorker_RunAsync(LCUI_Worker worker);
Expand Down
45 changes: 32 additions & 13 deletions src/worker.c
Original file line number Diff line number Diff line change
Expand Up @@ -69,24 +69,35 @@ void LCUIWorker_PostTask(LCUI_Worker worker, LCUI_Task task)
LCUIMutex_Unlock(&worker->mutex);
}

LCUI_BOOL LCUIWorker_RunTask(LCUI_Worker worker)
LCUI_Task LCUIWorker_GetTask(LCUI_Worker worker)
{
LCUI_Task task;
LinkedListNode *node;
LCUIMutex_Lock(&worker->mutex);

node = LinkedList_GetNode(&worker->tasks, 0);
if (node) {
task = node->data;
LinkedList_Unlink(&worker->tasks, node);
LCUIMutex_Unlock(&worker->mutex);
LCUITask_Run(task);
LCUITask_Destroy(task);
free(task);
free(node);
return TRUE;
if (!node) {
return NULL;
}
task = node->data;
LinkedList_Unlink(&worker->tasks, node);
free(node);
return task;
}

LCUI_BOOL LCUIWorker_RunTask(LCUI_Worker worker)
{
LCUI_Task task;

LCUIMutex_Lock(&worker->mutex);
task = LCUIWorker_GetTask(worker);
LCUIMutex_Unlock(&worker->mutex);
return FALSE;
if (!task) {
return FALSE;
}
LCUITask_Run(task);
LCUITask_Destroy(task);
free(task);
return TRUE;
}

static void OnDeleteTask(void *arg)
Expand All @@ -106,10 +117,18 @@ static void LCUIWorker_ExecDestroy(LCUI_Worker worker)

static void LCUIWorker_Thread(void *arg)
{
LCUI_Task task;
LCUI_Worker worker = arg;

LCUIMutex_Lock(&worker->mutex);
while (worker->active) {
if (LCUIWorker_RunTask(worker)) {
task = LCUIWorker_GetTask(worker);
if (task) {
LCUIMutex_Unlock(&worker->mutex);
LCUITask_Run(task);
LCUITask_Destroy(task);
free(task);
LCUIMutex_Lock(&worker->mutex);
continue;
}
if (worker->active) {
Expand Down

0 comments on commit 2b41f54

Please sign in to comment.