Skip to content

mfkiwl/cross-platform-threads

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cross-Platform Threads

Cross-platform threads and mutexes without any overhead.

Installation

Copy this library into a project and include the header files.

#include "thread.h"
#include "mutex.h"

Usage

Threads

  1. Define a thread handler
DEF_THREAD_HANDLER(worker) {
  // Code here...
  return 0;
}
  1. Spawn a thread
Thread thread;
thread_spawn(&thread, worker, NULL);
  1. Join with the thread
thread_join(&thread);
  1. Destroy the thread
thread_destroy(&thread);

Mutexes

  1. Initialize a mutex
Mutex mutex;
mutex_init(&mutex);
  1. Lock the mutex
mutex_lock(&mutex);
  1. Unlock the mutex
mutex_unlock(&mutex);
  1. Destroy the mutex
mutex_destroy(&mutex);

Additional Functions

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);

Example

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;
}

About

Cross-platform threads and mutexes without any overhead.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • C 91.3%
  • C++ 8.7%