Windows thread pool.

This commit is contained in:
Christoffer Lerno
2023-06-02 22:34:02 +02:00
committed by Christoffer Lerno
parent d0e8944c56
commit cfd21f8ca2
2 changed files with 52 additions and 2 deletions

View File

@@ -51,8 +51,58 @@ void taskqueue_run(int threads, Task **task_list)
pthread_mutex_destroy(&queue.lock);
}
#else
#elif PLATFORM_WINDOWS
#include <Windows.h>
#include <process.h>
typedef struct TaskQueue_
{
CRITICAL_SECTION lock;
Task **queue;
} TaskQueue;
static DWORD WINAPI taskqueue_thread(LPVOID lpParam)
{
TaskQueue *task_queue = (TaskQueue *)lpParam;
bool is_active = false;
while (1)
{
EnterCriticalSection(&task_queue->lock);
unsigned task_count = vec_size(task_queue->queue);
if (!task_count) goto SHUTDOWN;
Task *task = (Task*)task_queue->queue[task_count - 1];
vec_pop(task_queue->queue);
LeaveCriticalSection(&task_queue->lock);
task->task(task->arg);
}
SHUTDOWN:
LeaveCriticalSection(&task_queue->lock);
return 0;
}
void taskqueue_run(int threads, Task **task_list)
{
assert(threads > 0);
HANDLE *handles = malloc(sizeof(HANDLE) * (unsigned)threads);
TaskQueue queue = { .queue = task_list };
InitializeCriticalSection(&queue.lock);
for (int i = 0; i < threads; i++)
{
handles[i] = (HANDLE)_beginthreadex(NULL, 0, taskqueue_thread, &queue, 0, NULL);
if (handles[i] == NULL) error_exit("Fail to set up thread pool");
}
WaitForMultipleObjects(threads, handles, TRUE, INFINITE);
for (int i = 0; i < threads; i++)
{
CloseHandle(handles[i]);
}
free((void*)handles);
DeleteCriticalSection(&queue.lock);
}
#else
void taskqueue_run(int threads, Task **task_list)
{

View File

@@ -1 +1 @@
#define COMPILER_VERSION "0.4.521"
#define COMPILER_VERSION "0.4.522"