Skip to content

Instantly share code, notes, and snippets.

@RealNeGate
Last active February 15, 2022 09:58
Show Gist options
  • Select an option

  • Save RealNeGate/7abb9a7b71bb60ee9a07cfc4c43b9a8c to your computer and use it in GitHub Desktop.

Select an option

Save RealNeGate/7abb9a7b71bb60ee9a07cfc4c43b9a8c to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdatomic.h>
#include <threads.h>
#define NUM_THREADS 8
static _Atomic size_t tasks_reserved;
static _Atomic size_t tasks_complete;
static size_t tasks_count;
static void do_task(size_t t) {
// ...
printf("Boo! %zu\n", t);
}
static int task_thread(void* param) {
while (true) {
size_t t = tasks_reserved++;
if (t >= tasks_count) {
// we're done, just waiting on the tasks
// on the other threads to be completed.
// wait until it's completed
while (tasks_complete < tasks_count) {
thrd_yield();
}
continue;
}
do_task(t);
tasks_complete++;
}
return 0;
}
static void parallel_dispatch(size_t count) {
tasks_count = count;
tasks_complete = 0;
tasks_reserved = 0;
// lazy init some threads into existence
static thrd_t threads[NUM_THREADS];
static bool made_threads = false;
if (!made_threads) {
made_threads = true;
for (int i = 0; i < NUM_THREADS; i++) {
thrd_create(&threads[i], task_thread, NULL);
}
}
// wait until it's completed
while (tasks_complete < tasks_count) {
thrd_yield();
}
}
int main() {
parallel_dispatch(100);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment