【c创建线程的四种方式】在C语言中,虽然标准库本身不直接提供多线程支持,但通过引入POSIX线程(pthread)库或C11标准中的`
一、使用POSIX线程(pthread)
POSIX线程是Linux系统中广泛使用的多线程接口,适用于Unix/Linux环境。
- 函数:`pthread_create()`
- 特点:
- 需要链接`-pthread`编译选项
- 支持线程同步与互斥锁
- 线程间共享内存空间
```c
include
include
void thread_func(void arg) {
printf("Thread is running.\n");
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
pthread_join(tid, NULL);
return 0;
}
```
二、使用C11标准的`
C11标准引入了`
- 函数:`thrd_create()`
- 特点:
- 跨平台兼容性好(Windows、Linux、macOS)
- 语法简洁,适合现代C项目
- 不支持所有POSIX特性
```c
include
include
int thread_func(void arg) {
printf("Thread is running.\n");
return 0;
}
int main() {
thrd_t tid;
thrd_create(&tid, thread_func, NULL);
thrd_join(tid, NULL);
return 0;
}
```
三、使用Boost.Thread(非标准库)
Boost是一个流行的C++库,其中的`Boost.Thread`模块支持C++的多线程功能。
- 适用场景:C++项目中使用Boost库时
- 特点:
- 功能强大,支持任务调度、异步操作等
- 需要安装Boost库并链接相关依赖
```cpp
include
include
void thread_func() {
std::cout << "Thread is running." << std::endl;
}
int main() {
boost::thread t(thread_func);
t.join();
return 0;
}
```
> 注意:Boost.Thread属于C++扩展,并非C语言标准库。
四、使用Windows API(仅限Windows系统)
在Windows平台上,可以通过`CreateThread()`函数创建线程。
- 函数:`CreateThread()`
- 特点:
- 仅适用于Windows系统
- 与Windows内核紧密集成
- 使用`WaitForSingleObject()`等待线程结束
```c
include
include
DWORD WINAPI ThreadProc(LPVOID lpParam) {
printf("Thread is running.\n");
return 0;
}
int main() {
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}
```
总结对比表
| 方式 | 是否标准 | 平台支持 | 是否需额外依赖 | 适用场景 |
| POSIX线程(pthread) | 非标准(POSIX) | Linux/Unix | 是(需链接`-pthread`) | Linux开发、服务器程序 |
| C11 ` | 标准(C11) | 跨平台 | 否 | 现代C项目、跨平台开发 |
| Boost.Thread | 非标准(C++库) | 跨平台 | 是(需安装Boost) | C++项目、需要高级功能 |
| Windows API(CreateThread) | 非标准 | Windows | 否 | Windows平台应用开发 |
以上四种方式各有优劣,选择时应根据项目需求、平台限制和开发习惯综合考虑。对于C语言开发而言,推荐优先使用POSIX线程或C11标准库,以保证代码的可移植性和可维护性。


