cthread is a small, user-space threading library written in C (can compare it to green threads in early Java) that trades true parallelism and kernel support for speed, simplicity, and control . It provides basic thread creation, yielding, joining, locking, and thread-safe memory management. This library is intended for educational purposes and small-scale concurrent applications, demonstrating how threading works at a low level.
-
Create user threads with a simple API
-
Thread yielding for cooperative scheduling
-
Thread joining to wait for a thread to finish
-
Idle thread and thread recycling to manage resources efficiently
-
Thread-safe memory allocator integration
-
Simple thread locking mechanism via mutual exclusion
Clone the repository and compile your project with cthread.c:
git clone https://github.com/yourusername/cthread.git
cd cthread
gcc -o my_program my_program.c cthread.c context_switch.S -I.
Note: memory_allocator.c (included in cthread) is required for thread stack allocation. You may wish to use a standard memory allocator (I used it for testing my own memory allocator).
INIT_THREAD_ENV() Initializes the thread system
DEL_THREAD_ENV() Cleans up all threads and resources
thread_create(fn, args) Creates a new thread executing fn with args
thread_yield() Yields execution to another ready thread
thread_exit() Terminates the current thread
thread_join(thread, &return_val) Waits for a thread to finish and retrieves its return value
thread_mutex (flag) Synchronization primitive that ensures only one thread accesses critical section to prevent undefined behavior
-
Preemptive Scheduling: Currently cooperative; adding timers and signals for preemptive multitasking would improve responsiveness.
-
Multiple priority queues: Support threads with different priorities.
-
Enahnced thread locking features: Improve security of data by implementing semaphores.
-
Dynamic stack resizing: Automatically resize thread stacks if needed.
-
Error handling & logging: More robust handling for invalid operations.
-
Cross-platform support: Adapt to other architectures beyond x86-64.
-
Format/Document Code a bit more cleanly.
Contributions are welcome!!! You can help by:
Fixing bugs, adding new features
Improving scheduling logic
Adding tests and benchmarks
Enhancing documentation
MIT License