【看到哪里写到哪里】如何在C中使用多进程设计(1)
C11开始,在<threads.h>中定义了关于多进程设计函数。但是在MSYS中支持能有限。很不好用。
如何纯粹是想学习C的多线程设计,可以使用一个轻量级的TinyCThread的C11 线程库实现,非常简单实用。
TinyCThread是一个轻量级的 C11 线程库实现,专为嵌入式系统和资源受限环境设计。它提供了与 C11 <threads.h>
兼容的 API,但无需完整的 C11 编译器支持。以下是其使用方法和示例:
1. 集成 tinythread.h
- 下载源码:从 GitHub
https://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. 编译与链接
Windows(MinGW/MSYS)
gcc -std=c99 -pthread your_file.c tinythread.c -o output
或者在VSCode,添加-pthread,编译即可。
4.特性与限制
-
优势:
- 纯 C 实现,无依赖,适合嵌入式系统。
- 兼容 C11
<threads.h>
,学习成本低。 - 支持跨平台(POSIX、Windows、WebAssembly 等)。
-
限制:
- 不支持 C11 原子操作(需单独使用
stdatomic.h
)。 - 部分高级功能缺失(如线程局部存储)。
- 不支持 C11 原子操作(需单独使用