Skip to content

Commit 2b41f54

Browse files
committedMar 4, 2019
fix(worker): task queue should not be blocked when running a task
1 parent fc54a64 commit 2b41f54

File tree

2 files changed

+34
-13
lines changed

2 files changed

+34
-13
lines changed
 

‎include/LCUI/worker.h

+2
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ LCUI_API LCUI_Worker LCUIWorker_New(void);
4141

4242
LCUI_API void LCUIWorker_PostTask(LCUI_Worker worker, LCUI_Task task);
4343

44+
LCUI_API LCUI_Task LCUIWorker_GetTask(LCUI_Worker worker);
45+
4446
LCUI_API LCUI_BOOL LCUIWorker_RunTask(LCUI_Worker worker);
4547

4648
LCUI_API int LCUIWorker_RunAsync(LCUI_Worker worker);

‎src/worker.c

+32-13
Original file line numberDiff line numberDiff line change
@@ -69,24 +69,35 @@ void LCUIWorker_PostTask(LCUI_Worker worker, LCUI_Task task)
6969
LCUIMutex_Unlock(&worker->mutex);
7070
}
7171

72-
LCUI_BOOL LCUIWorker_RunTask(LCUI_Worker worker)
72+
LCUI_Task LCUIWorker_GetTask(LCUI_Worker worker)
7373
{
7474
LCUI_Task task;
7575
LinkedListNode *node;
76-
LCUIMutex_Lock(&worker->mutex);
76+
7777
node = LinkedList_GetNode(&worker->tasks, 0);
78-
if (node) {
79-
task = node->data;
80-
LinkedList_Unlink(&worker->tasks, node);
81-
LCUIMutex_Unlock(&worker->mutex);
82-
LCUITask_Run(task);
83-
LCUITask_Destroy(task);
84-
free(task);
85-
free(node);
86-
return TRUE;
78+
if (!node) {
79+
return NULL;
8780
}
81+
task = node->data;
82+
LinkedList_Unlink(&worker->tasks, node);
83+
free(node);
84+
return task;
85+
}
86+
87+
LCUI_BOOL LCUIWorker_RunTask(LCUI_Worker worker)
88+
{
89+
LCUI_Task task;
90+
91+
LCUIMutex_Lock(&worker->mutex);
92+
task = LCUIWorker_GetTask(worker);
8893
LCUIMutex_Unlock(&worker->mutex);
89-
return FALSE;
94+
if (!task) {
95+
return FALSE;
96+
}
97+
LCUITask_Run(task);
98+
LCUITask_Destroy(task);
99+
free(task);
100+
return TRUE;
90101
}
91102

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

107118
static void LCUIWorker_Thread(void *arg)
108119
{
120+
LCUI_Task task;
109121
LCUI_Worker worker = arg;
122+
110123
LCUIMutex_Lock(&worker->mutex);
111124
while (worker->active) {
112-
if (LCUIWorker_RunTask(worker)) {
125+
task = LCUIWorker_GetTask(worker);
126+
if (task) {
127+
LCUIMutex_Unlock(&worker->mutex);
128+
LCUITask_Run(task);
129+
LCUITask_Destroy(task);
130+
free(task);
131+
LCUIMutex_Lock(&worker->mutex);
113132
continue;
114133
}
115134
if (worker->active) {

0 commit comments

Comments
 (0)
Please sign in to comment.