Skip to content

Emulated C11 threads and thread pool using Pthreads or Pthreads4w

License

Notifications You must be signed in to change notification settings

zelang-dev/cthread

 
 

Repository files navigation

C Thread, emulated C11 and thread pool

Using Pthreads, or Pthreads4w.

The Windows build in deps folder, this fork has ABI differences, see original README.md. And this build and all general memory allocations based on standard malloc/stdlib.h replaced with forked rpmalloc that has no dependency on thread_local.

This branch has some changes to be able to be compiled using Tiny C compiler.

CThread is a minimal, portable implementation of basic threading classes for C. They closely mimic the functionality and naming of the C11 standard, and should be easily replaceable with the corresponding standard variants. This package also integrates C89 compatible atomics for C11 Atomic support.

All malloc operations are lockless, and also implements emulated Thread-local storage via macro thread_storage(type, variable) as:

example.h

#include "cthread.h"
#include <stdio.h>
#include <assert.h>
thread_storage_create(int, gLocalVar);

example.c

#include "example.h"
#define THREAD_COUNT 5

thread_storage(int, gLocalVar)

static int thread_local_storage(void *aArg) {
    int thread = *(int *)aArg;
    free(aArg);

    int data = thread + rand();
    *gLocalVar() = data;
    printf("thread #%d, gLocalVar is: %d\n", thread, *gLocalVar());
    assert(*gLocalVar() == data);
    return 0;
}

void emulated_tls(void) {
    thrd_t t[THREAD_COUNT];
    *gLocalVar() = 1;

    for (int i = 0; i < THREAD_COUNT; i++) {
        int *n = malloc(sizeof * n);
        *n = i;
        thrd_create(t + i, thread_local_storage, n);
    }

    for (int i = 0; i < THREAD_COUNT; i++) {
        thrd_join(t[i], NULL);
    }

    assert(*gLocalVar() == 1);
}

int main(void) {
    emulated_tls();
    return 0;
}

This package implements thrd_local(type, variable) macro, same behavior as above, but will not emulate if feature is available in your compiler, should be used for cross compatibility calling.

Packages

No packages published

Languages

  • C 88.2%
  • C++ 10.5%
  • Other 1.3%