Cross-platform threads and mutexes without any overhead.
Copy this library into a project and include the header files.
#include "thread.h"
#include "mutex.h"- Define a thread handler
DEF_THREAD_HANDLER(worker) {
// Code here...
return 0;
}- Spawn a thread
Thread thread;
thread_spawn(&thread, worker, NULL);- Join with the thread
thread_join(&thread);- Destroy the thread
thread_destroy(&thread);- Initialize a mutex
Mutex mutex;
mutex_init(&mutex);- Lock the mutex
mutex_lock(&mutex);- Unlock the mutex
mutex_unlock(&mutex);- Destroy the mutex
mutex_destroy(&mutex);Get the number of CPU cores
unsigned int num_cores = get_num_cores();Join multiple threads
thread_join_multi(&threads, thread_count);Lock multiple mutexes
mutex_lock_multi(&mutexes, mutex_count);The following is an example of a small program using this library.
#include <stdlib.h>
#include "thread.h"
DEF_THREAD_HANDLER(worker) {
// Do work...
return 0;
}
int main() {
unsigned int thread_count = get_num_cores();
Thread *threads = malloc(thread_count * sizeof(Thread));
for (unsigned int i = 0; i < thread_count; i++) {
thread_spawn(&threads[i], worker, NULL);
}
thread_join_multi(threads, thread_count);
for (unsigned int i = 0; i < thread_count; i++) {
thread_destroy(&threads[i]);
}
free(threads);
return EXIT_SUCCESS;
}