免费做自我介绍网站,网站建设要多久,宠物托运网站开发,visio做网站效果C11开始#xff0c;在threads.h中定义了关于多进程设计函数。但是在MSYS中支持能有限。很不好用。
如何纯粹是想学习C的多线程设计#xff0c;可以使用一个轻量级的TinyCThread的C11 线程库实现#xff0c;非常简单实用。 TinyCThread是一个轻量级的 C11 线程库实现…C11开始在threads.h中定义了关于多进程设计函数。但是在MSYS中支持能有限。很不好用。
如何纯粹是想学习C的多线程设计可以使用一个轻量级的TinyCThread的C11 线程库实现非常简单实用。 TinyCThread是一个轻量级的 C11 线程库实现专为嵌入式系统和资源受限环境设计。它提供了与 C11 threads.h 兼容的 API但无需完整的 C11 编译器支持。以下是其使用方法和示例
1. 集成 tinythread.h
下载源码从 GitHubhttps://github.com/tinycthread/tinycthread 获取 tinythread.h 和 tinythread.c。添加到项目将这两个文件复制到你的项目目录。然后在程序中添加 #include tinycthread.h编译选项无需特殊编译器支持C99 即可但需链接线程库如 -pthread。 2. 核心 API
tinythread.h 提供了与 C11 threads.h 兼容的接口
线程管理
typedef struct thrd_t thrd_t; // 线程类型int thrd_create(thrd_t *thr, thrd_start_t func, void *arg); // 创建线程
int thrd_join(thrd_t thr, int *res); // 等待线程结束
int thrd_detach(thrd_t thr); // 分离线程
thrd_t thrd_current(void); // 获取当前线程
int thrd_equal(thrd_t t1, thrd_t t2); // 比较线程ID
void thrd_yield(void); // 让出CPU互斥锁Mutex
typedef struct mtx_t mtx_t;int mtx_init(mtx_t *mtx, int type); // 初始化互斥锁
void mtx_destroy(mtx_t *mtx); // 销毁互斥锁
int mtx_lock(mtx_t *mtx); // 加锁
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts); // 带超时加锁
int mtx_trylock(mtx_t *mtx); // 尝试加锁
int mtx_unlock(mtx_t *mtx); // 解锁条件变量
typedef struct cnd_t cnd_t;int cnd_init(cnd_t *cnd); // 初始化条件变量
void cnd_destroy(cnd_t *cnd); // 销毁条件变量
int cnd_wait(cnd_t *cnd, mtx_t *mtx); // 等待条件变量
int cnd_timedwait(cnd_t *cnd, mtx_t *mtx, const struct timespec *ts); // 带超时等待
int cnd_signal(cnd_t *cnd); // 唤醒一个等待线程
int cnd_broadcast(cnd_t *cnd); // 唤醒所有等待线程3. 编译与链接
WindowsMinGW/MSYS
gcc -stdc99 -pthread your_file.c tinythread.c -o output
或者在VSCode添加-pthread,编译即可。 4.特性与限制 优势 纯 C 实现无依赖适合嵌入式系统。兼容 C11 threads.h学习成本低。支持跨平台POSIX、Windows、WebAssembly 等。 限制 不支持 C11 原子操作需单独使用 stdatomic.h。部分高级功能缺失如线程局部存储。