{"id":19878562,"url":"https://github.com/dezashibi-c/dthreads","last_synced_at":"2026-04-12T02:35:28.049Z","repository":{"id":253264631,"uuid":"840612134","full_name":"dezashibi-c/dthreads","owner":"dezashibi-c","description":"Cross platform multi threading library with maximum possible familiarity of pthreads and using native api for windows.","archived":false,"fork":false,"pushed_at":"2024-08-23T11:14:32.000Z","size":292,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-03-01T02:32:55.266Z","etag":null,"topics":["cross-platform","gcc","linux","multi-threading","osx","pthread","threads","windows","windows-api"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dezashibi-c.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGE_LOGS.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-10T06:41:26.000Z","updated_at":"2024-08-23T11:14:35.000Z","dependencies_parsed_at":"2024-08-19T04:32:35.133Z","dependency_job_id":"cf64b04b-cdff-4818-ab00-82b6a9420bb6","html_url":"https://github.com/dezashibi-c/dthreads","commit_stats":null,"previous_names":["dezashibi-c/dthreads"],"tags_count":13,"template":false,"template_full_name":null,"purl":"pkg:github/dezashibi-c/dthreads","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dezashibi-c%2Fdthreads","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dezashibi-c%2Fdthreads/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dezashibi-c%2Fdthreads/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dezashibi-c%2Fdthreads/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dezashibi-c","download_url":"https://codeload.github.com/dezashibi-c/dthreads/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dezashibi-c%2Fdthreads/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31702580,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-11T21:17:31.016Z","status":"online","status_checked_at":"2026-04-12T02:00:06.763Z","response_time":58,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cross-platform","gcc","linux","multi-threading","osx","pthread","threads","windows","windows-api"],"created_at":"2024-11-12T17:05:55.570Z","updated_at":"2026-04-12T02:35:28.014Z","avatar_url":"https://github.com/dezashibi-c.png","language":"C","readme":"# 👉👉 NOTE\n\n## This is not fully completed, I'm working on it, and am open to hear what you think\n\nHere are a couple of areas that I would like to get help or opinions:\n\n- [ ] Random number generator behavior improvement, especially on Windows refer to [here](https://github.com/dezashibi-c/dthreads/blob/0fd1c7339f26b0d6409b6ae8ac03d981cd795c4a/dthreads/_headers/random.h#L82).\n- [ ] haven't tested it with `cpp` yet\n- [x] `osx` compilation failure is not fixed yet\n- [ ] Can I consider it feature completed? any suggestions?\n- [x] Comments and documentations are not yet fully reviewed\n- [x] API declarations need review (for more cross-compiler support and also dynamic linking)\n\n# DThreads: Cross-Platform Threading Library in C\n\nAfter using [CThreads](https://github.com/PerformanC/CThreads) by [@ThePedroo](https://github.com/ThePedroo) at [a specific commit](https://github.com/PerformanC/CThreads/commit/805673c9161f62e542ada76080d59516da5d17fd) in the repository (since there were no tags or version numbers), I found the need to adapt and re-implement it to fit [my coding style](https://github.com/dezashibi-c/.github/blob/main/coding_style.md) and preferences to have a simpler, more compatible with Windows API (the result from thread had bug) and more feature-rich version.\n\nThis library is based on the ideas from `CThreads` as the initial inspiration with a significant re-implementation with additional functionality and design choices.\n\n**👉 NOTE:** In accordance with the original BSD 2-Clause License of `CThreads`, I acknowledge the work of [@ThePedroo](https://github.com/ThePedroo). This project includes substantial re-implementations, modifications and additions, and is distributed under the BSD 3-Clause License. The original `CThreads` license is included in this project, ensuring compliance with open-source licensing requirements.\n\n## Overview\n\nDThreads is a cross-platform threading library designed for C programmers who need a consistent and simple API to manage threads, synchronization primitives, and other concurrency utilities across different operating systems. It abstracts the complexities of native threading APIs like POSIX threads and Windows threads, providing a unified interface that works seamlessly on both platforms.\n\n## Design Philosophy\n\nThe core philosophy behind DThreads is to create a minimalistic, yet powerful, threading library that emphasizes portability, simplicity, and performance. By abstracting the differences between POSIX and Windows threading mechanisms, DThreads allows programmers to write multithreaded code once and run it on multiple platforms without modification.\n\n**👉 NOTE:** When implementing `dthreads` library, despite trying to keep the API closer to `pthread` but my assumption was the programmer wants single source of truth so the documentation tried to explain things more in detail rather than referring to original API documentations for `pthread` and Windows API.\n\n### Key Design Choices\n\n- **Cross-Platform Compatibility**: DThreads provides a unified API that works across different platforms, hiding the underlying implementation details.\n\n**👉 NOTE:** The goal is to provide cross-platform compatibility for modern desktop systems and platforms, so you have to make sure certain features are available on your machine, you can suggest platform support via issue section.\n\n- **Modularity**: I've not been a friend of everything all at one place, so I've decided to modularize the implementations for each platform to its corresponding header and source file.\n- **Simplicity**: The API is designed to be easy to use, with clear and concise function signatures and configuration structures.\n- **Performance**: DThreads aims to minimize overhead by using lightweight structures and efficient synchronization primitives.\n- **Code Clarity**: The library encourages a clear and consistent coding style, with well-documented functions and macros to reduce the learning curve.\n\n## API Overview\n\n**👉 For detailed documentation refer to [dthread.h](/dthreads/dthread.h).**\n\n### Thread Management\n\n- **DThreadRoutine**: A function pointer type for thread routines. A thread routine is a function that accepts a single `void*` argument and returns a `void*`.\n- **dthread_define_routine**: A macro to simplify the definition of thread routines. It ensures compatibility with the DThreads library.\n- **dthread_set_data**: A macro that sets thread data for given thread reference.\n- **dthread_set_func**: A macro that sets thread routine for given thread reference.\n- **dthread_get_result**: A macro that gets thread routine result after the thread join completes for given thread reference.\n- **dthread_get_result_as**: A macro that gets thread routine result after the thread join completes for given thread reference and casting it to given type (must be a pointer type).\n- **dthread_create**: Creates a new thread using the specified configuration and attributes.\n- **dthread_detach**: Detaches a thread, allowing it to run independently. Once detached, a thread cannot be joined.\n- **dthread_join**: Waits for a thread to complete, blocking the calling thread until the specified thread terminates.\n- **dthread_equal**: Compares two threads for equality.\n- **dthread_self**: Returns a `DThread` structure representing the current thread.\n- **dthread_id**: Returns the unique identifier of a thread.\n- **dthread_exit**: Exits the calling thread and optionally returns a value to the thread that joined it.\n- **dthread_cancel**: Sends a cancellation request to the specified thread.\n\n### Synchronization Primitives\n\n- **Mutexes**:\n  - **dthread_mutex_init**: Initializes a mutex with optional attributes.\n  - **dthread_mutex_lock**: Locks a mutex, blocking the calling thread if necessary.\n  - **dthread_mutex_trylock**: Attempts to lock a mutex without blocking.\n  - **dthread_mutex_unlock**: Unlocks a mutex.\n  - **dthread_mutex_destroy**: Destroys a mutex, releasing its resources.\n\n- **Condition Variables**:\n  - **dthread_cond_init**: Initializes a condition variable with optional attributes.\n  - **dthread_cond_signal**: Signals a condition variable, waking one waiting thread.\n  - **dthread_cond_broadcast**: Broadcasts a condition variable, waking all waiting threads.\n  - **dthread_cond_destroy**: Destroys a condition variable, releasing its resources.\n  - **dthread_cond_wait**: Waits on a condition variable, releasing the associated mutex and blocking the calling thread until the condition is signaled.\n\n**👉 NOTE:** If you want to make sure `clock` in condition attributes and`robust` in mutex atributes are available in your desired `POSIX` system you can check if `DTHREAD_MUTEX_ROBUST_AND_COND_CLOCK_AVAILABLE` is defined.\n\n### Advanced Features (Optional)\n\n- **Read-Write Locks**:\n  - **dthread_rwlock_init**: Initializes a read-write lock.\n  - **dthread_rwlock_rdlock**: Acquires a read lock on the read-write lock.\n  - **dthread_rwlock_unlock**: Unlocks the read-write lock.\n  - **dthread_rwlock_wrlock**: Acquires a write lock on the read-write lock.\n  - **dthread_rwlock_destroy**: Destroys the read-write lock.\n  \n- **Barriers**:\n  - **dthread_barrier_init**: Initializes a barrier for a specified number of threads.\n  - **dthread_barrier_wait**: Waits at a barrier until the specified number of threads have reached the barrier.\n  - **dthread_barrier_destroy**: Destroys the barrier, releasing its resources.\n  \n- **Semaphores**:\n  - **dthread_semaphore_init**: Initializes a semaphore with the specified initial value.\n  - **dthread_semaphore_wait**: Waits on a semaphore, decrementing its value.\n  - **dthread_semaphore_post**: Posts to a semaphore, incrementing its value.\n  - **dthread_semaphore_destroy**: Destroys the semaphore, releasing its resources.\n\n### Thread Safe Random Number Generator\n\n- **dthread_rng_init**: Initializes the mutex for thread-safe random number generation.\n- **dthread_rng_cleanup**: Cleans up the mutex used for thread-safe random number generation.\n- **dthread_rng_random**: Generates a thread-safe random number.\n- **dthread_rng_seed_maker**: Seeds the random number generator with a unique seed.\n\n**👉 NOTE: Checkout [trylock.c](/examples/trylock.c) for learning more about using thread safe random number generator.**\n\n### Types Documentation\n\n**👉 NOTE:** Types are defined in [dthread.h](/dthreads/dthread.h) and in the library's [windows.h](/dthreads/_headers/windows.h) and [posix.h](/dthreads/_headers/posix.h) based on the operating system accordingly. You can find the overall definition and purpose of each type below.\n\n- **`DThread`**  \n  Represents a thread in the DThreads library.  \n  The `DThread` structure is used to manage and identify individual threads created and managed by the DThreads library. It abstracts the underlying platform-specific thread representation. It also holds the reference to thread routine, thread routine data and thread result.\n\n  **👉 Initialization:** You can initialize a thread by using `dthread_init_thread` macro, refer to examples below.\n\n- **`DThreadAttr`**  \n  Attributes for thread creation.  \n  The `DThreadAttr` structure is used to specify attributes for threads when they are created. This includes options like stack size, thread priority, and other platform-specific attributes that influence the behavior of the thread.\n\n- **`DThreadMutex`**  \n  Represents a mutex (mutual exclusion) in the DThreads library.  \n  The `DThreadMutex` structure is used to protect shared resources from concurrent access by multiple threads. It provides locking mechanisms to ensure that only one thread can access a critical section at a time.\n\n- **`DThreadMutexAttr`**  \n  Attributes for mutex creation.  \n  The `DThreadMutexAttr` structure is used to specify attributes for mutexes when they are initialized. This includes options like mutex type (normal, recursive, or error-checking) and other platform-specific attributes.\n\n- **`DThreadCond`**  \n  Represents a condition variable in the DThreads library.  \n  The `DThreadCond` structure is used for thread synchronization by allowing threads to wait until a particular condition is met. Condition variables are used in conjunction with mutexes to avoid race conditions.\n\n- **`DThreadCondAttr`**  \n  Attributes for condition variable creation.  \n  The `DThreadCondAttr` structure is used to specify attributes for condition variables when they are initialized. These attributes may vary depending on the underlying platform.\n\n- **`DThreadRWLock`**  \n  Represents a read-write lock in the DThreads library.  \n  The `DThreadRWLock` structure is used to provide read-write synchronization. It allows multiple threads to read shared data simultaneously, while ensuring exclusive access for write operations.\n\n- **`DThreadBarrier`**  \n  Represents a barrier in the DThreads library.  \n  The `DThreadBarrier` structure is used to synchronize a group of threads at a specific point in the program. All threads must reach the barrier before any can proceed past it.\n\n- **`DThreadSemaphore`**  \n  Represents a semaphore in the DThreads library.  \n  The `DThreadSemaphore` structure is used to control access to a resource by multiple threads. Semaphores are used to limit the number of threads that can access a resource concurrently.\n\n## Usage Guide\n\n**👉 NOTE: You can get the latest `rc`, `beta`, or stable version from releases. You can use the following commands:**\n\n- the latest release:\n\n```bash\n wget https://github.com/dezashibi-c/dthreads/releases/download/$(curl -s https://api.github.com/repos/dezashibi-c/dthreads/releases/latest | grep -oP '\"tag_name\": \"\\K(.*)(?=\")')/dthreads.zip\n```\n\n- the specific version (remember to change `\u003cversion\u003e` with the version you need)\n\n```bash\nwget https://github.com/dezashibi-c/dthreads/releases/download/\u003cversion\u003e/dthreads.zip\n```\n\n### Including DThreads in Your Project\n\n**👉 NOTE: Make sure `#define DTHREAD_IMPL` is included in exactly one of your source files.**\n\n**👉 NOTE: Make sure to check out the [examples folder](/examples/) for usage examples.**\n\n**👉 NOTE: Running `make` on the root of the cloned repo builds all the [examples folder](/examples/).**\n\n**👉 NOTE: You can run all the tests all at once by running `make test`.**\n\n**👉 NOTE: Don't forget to add `-lpthread` when compiling on POSIX operating systems.**\n\nTo include DThreads in your project, add the `dthreads/dthread.h` header file to your source files and link against the appropriate implementation for your platform (POSIX or Windows).\n\n```c\n#define DTHREAD_IMPL\n#include \"dthreads/dthread.h\"\n```\n\n### Creating a Thread\n\nTo create a thread, define a thread routine and use `dthread_create` to start the thread:\n\n```c\n#include \"dthreads/dthread.h\"\n\ndthread_define_routine(my_thread_function) {\n    // Thread code here\n    return NULL;\n}\n\nint main() {\n    DThread thread = dthread_init_thread(my_thread_function, NULL);\n\n    dthread_create(\u0026thread, NULL);\n    dthread_join(\u0026thread);\n    return 0;\n}\n```\n\n### Using Mutexes\n\nMutexes are used to protect shared resources from concurrent access:\n\n```c\nDThreadMutex mutex;\ndthread_mutex_init(\u0026mutex, NULL);\n\ndthread_mutex_lock(\u0026mutex);\n// Critical section\ndthread_mutex_unlock(\u0026mutex);\n\ndthread_mutex_destroy(\u0026mutex);\n```\n\n### Condition Variables\n\nCondition variables are used to block a thread until a particular condition is met:\n\n```c\nDThreadCond cond;\nDThreadMutex mutex;\n\ndthread_cond_init(\u0026cond, NULL);\ndthread_mutex_init(\u0026mutex, NULL);\n\ndthread_mutex_lock(\u0026mutex);\nwhile (condition_not_met()) {\n    dthread_cond_wait(\u0026cond, \u0026mutex);\n}\ndthread_mutex_unlock(\u0026mutex);\n\ndthread_cond_signal(\u0026cond);\ndthread_cond_destroy(\u0026cond);\ndthread_mutex_destroy(\u0026mutex);\n```\n\n### Using Semaphores\n\nSemaphores control access to a resource by multiple threads:\n\n```c\nDThreadSemaphore semaphore;\ndthread_semaphore_init(\u0026semaphore, 3); // Initialize with a count of 3\n\ndthread_semaphore_wait(\u0026semaphore);\n// Access the resource\ndthread_semaphore_post(\u0026semaphore);\n\ndthread_semaphore_destroy(\u0026semaphore);\n```\n\n### Barriers\n\nBarriers are used to synchronize a group of threads:\n\n```c\nDThreadBarrier barrier;\ndthread_barrier_init(\u0026barrier, 5); // Barrier for 5 threads\n\ndthread_barrier_wait(\u0026barrier);\n// Code that executes after all threads reach the barrier\n\ndthread_barrier_destroy(\u0026barrier);\n```\n\n### Debugging Macro **(`DTHREAD_DEBUG`)**\n\nThis macro is used to control the logging of debug information within the DThreads library. When defined, it enables the `dthread_debug` and `dthread_debug_args` function macros, which logs internal operations and state changes. This is useful for development and troubleshooting but should be disabled in production builds to avoid performance overhead.\n\nYou can add whether `#define DTHREAD_DEBUG` before including the header file or passing `-DDTHREAD_DEBUG` to your compiler to activate debug messages.\n\n**👉 NOTE: Checkout [basic.c](/examples/basic.c) example to learn more.**\n\n- Output for `basic.c`\n\n```powershell\n\u003e.\\examples\\basic.exe\n\n----- value started at 12000\ndthread_mutex_init\ndthread_create\ndthread_create\ndthread_mutex_lock\ndthread_create\ndthread_mutex_lock\ndthread_mutex_lock\ndthread_create\n----- value is now 12001\ndthread_join\ndthread_mutex_lock\ndthread_mutex_unlock\n----- value is now 12002\ndthread_mutex_unlock\ndthread_join\ndthread_join\n----- value is now 12003\ndthread_mutex_unlock\n----- value is now 12004\ndthread_mutex_unlock\ndthread_join\ndthread_mutex_destroy\n----- value finished with 12004\nfinal result: 12004\n```\n\n### How to Use the `dthreads` Library in Shared Libraries\n\nThe `dthreads` library is designed to be used both as a static library and as a dynamic/shared library.\n\n#### 1. **Understanding the `DTHREAD_API` Macro**\n\nThe `dthreads` library uses a macro called `DTHREAD_API` to manage the export and import of symbols when building and using shared libraries. This macro adapts to different compilers and platforms to ensure that functions are correctly exported from the DLL (or shared object) and imported by any application or library that uses `dthreads`.\n\n- **`DTHREAD_API_EXPORT`**: Used when building the `dthreads` library to export functions and variables.\n- **`DTHREAD_API_IMPORT`**: Used when including `dthreads` in another project to import functions and variables from the shared library.\n- **`DTHREAD_DLL_EXPORTS`**: This macro should be defined when building the shared library to enable the export of symbols.\n\n#### 2. **Building the `dthreads` Library as a Shared Library**\n\nWhen compiling the `dthreads` library as a shared library, ensure that the `DTHREAD_DLL_EXPORTS` macro is defined. This will cause the `DTHREAD_API` macro to expand to `DTHREAD_API_EXPORT`, ensuring that all public functions and variables are exported from the DLL.\n\nExample command for building with MSVC:\n\n```sh\ncl /D DTHREAD_DLL_EXPORTS /LD dthread.c /o dthread.dll\n```\n\nExample command for building with GCC:\n\n```sh\ngcc -DDTHREAD_DLL_EXPORTS -shared -o libdthread.so dthread.c\n```\n\n#### 3. **Using the `dthreads` Library in Your Application**\n\nWhen using the `dthreads` library in your application or another shared library, you do **not** need to define `DTHREAD_DLL_EXPORTS`. This allows the `DTHREAD_API` macro to expand to `DTHREAD_API_IMPORT`, which ensures that the symbols are imported from the DLL.\n\n**👉 NOTE:** You only need this if you're creating another library based on `dthreads` and you need to choose to link it to your program statically or dynamically, otherwise just follow the normal way and add `DTHREAD_IMPL` in one of your `.c` source files and that does the work.\n\n## Contribution\n\nPlease consider **discussion in the issue section** for adding features or changing behaviors beforehand and please refer to [my coding style guide](https://github.com/dezashibi-c/.github/blob/main/coding_style.md) if you'd like to contribute.\n\n## Attributions\n\nThanks to [code-vault](https://code-vault.net) for providing various practical examples on their website so that I could test out my library properly.\n\n## License\n\nThis project is licensed under the BSD 3-Clause License.\n\nSome parts of this project are derived from the `CThreads` library by [@ThePedroo](https://github.com/ThePedroo), which is licensed under the BSD 2-Clause License. To comply with the terms of the BSD 2-Clause License, a copy of the original `CThreads` license is included in this repository under the [LICENSE](/LICENSE) file.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdezashibi-c%2Fdthreads","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdezashibi-c%2Fdthreads","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdezashibi-c%2Fdthreads/lists"}