ZoyaPatel

C 语言中多线程

SohaniSharma
 在 C 语言中多线程该选择哪种方式,是使用“自带的线程库(可能是你自己封装的)”、平台自带的线程(比如 Windows 的 Win32 Thread 或 Linux 的 pthreads),还是选择跨平台多线程库(像 C11 threads.h 或第三方库如 Boost.Thread)。我按几个维度详细分析:{alertInfo}

本文由人工编写审核,非AI生成内容,请放心观看!

{getToc} $title={文章目录}

1. 平台自带线程

1.1 Linux:pthread (POSIX threads)

  • 特点
    • POSIX 标准,几乎所有 UNIX-like 系统支持。
    • API 丰富:创建线程、互斥锁、条件变量、读写锁、线程局部存储等。
    • 低开销、性能稳定。
  • 优点
    • 精细控制线程行为。
    • 已经很成熟,文档和社区支持丰富。
  • 缺点
    • 不跨平台,Windows 不原生支持 pthread(可用 pthread-win32 移植)。
    • 编程相对底层,需要自己管理锁和同步。

示例:

#include <pthread.h>
#include <stdio.h>

void* thread_func(void* arg) {
    printf("Hello from thread\\n");
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    pthread_join(tid, NULL);
    return 0;
}

1.2 Windows:Win32 Thread (CreateThread)

  • 特点
    • Windows 原生线程 API。
    • 支持事件、互斥对象、信号量、IO 完成端口等。
  • 优点
    • 能用到 Windows 特有功能。
  • 缺点
    • 不跨平台。
    • API 与 POSIX 不兼容。

示例:

#include <windows.h>
#include <stdio.h>

DWORD WINAPI ThreadFunc(LPVOID lpParam) {
    printf("Hello from thread\\n");
    return 0;
}

int main() {
    HANDLE hThread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
    WaitForSingleObject(hThread, INFINITE);
    CloseHandle(hThread);
    return 0;
}

2. C11 标准线程库 threads.h

C11 标准引入了基础线程库:

#include <threads.h>

  • 特点
    • 标准化跨平台 API:thrd_create, mtx_lock, cnd_wait 等。
    • 基础同步功能都有。
  • 优点
    • 直接用标准库,理论上跨平台。
    • 简单,封装线程和同步。
  • 缺点
    • 实际支持有限:
      • GCC 默认不启用(需要 pthread<threads.h> 支持)。
      • Windows 支持较差(MSVC 最近才有部分实现)。
    • 功能不如 pthread 或 Win32 强大,适合轻量应用。

示例:

#include <threads.h>
#include <stdio.h>

int thread_func(void* arg) {
    printf("Hello from thread\\n");
    return 0;
}

int main() {
    thrd_t t;
    thrd_create(&t, thread_func, NULL);
    thrd_join(t, NULL);
    return 0;
}

3. 第三方跨平台库

  • 常用选择
    • Boost.Thread(C++)
    • APRlibuv(C,跨平台)
  • 特点
    • 封装底层平台差异。
    • 提供线程池、异步任务、高级同步工具。
  • 优点
    • 真正跨平台,不用写条件编译。
    • API 更高层,更易维护。
  • 缺点
    • 引入依赖。
    • 对纯 C 项目,可能过于重量级(Boost 基于 C++)。

4. 自带封装线程库

  • 概念
    • 有些项目会自己写一个跨平台线程封装,底层调用 pthread/Win32/其他。
  • 优点
    • 完全可控,API 可按项目需求定制。
  • 缺点
    • 工作量大,需要处理各种平台差异。
    • 容易出错。

5. 选择建议

场景 推荐方式 原因
Linux 或类 UNIX,要求性能 pthread 原生、成熟、文档丰富
Windows 专用 Win32 Thread 使用 Windows 特性
需要跨平台、简单需求 C11 threads.h 标准库,轻量
C++ 项目,跨平台复杂 Boost.Thread / std::thread 高级功能,线程池等
大型项目,控制权强 自己封装 可统一接口,但维护成本高

总结

  • 如果你只针对一个平台:直接用平台自带线程最稳。
  • 如果你追求跨平台:C11 threads.h 或自己封装一层平台接口。
  • 如果项目是 C++:用 std::thread 或 Boost.Thread 更方便。

总结

作为后端开发编程,一定要弄明白pthread 其他的可以完全不管,不顾,只需要认真学习!

版权声明:感谢您的阅读,资源整理自网络,如果您发现任何侵权行为,请联系 理科生网 管理人员,管理员将及时删除侵权内容。否则均为 理科生网 原创内容,转载时请务必以超链接(而非纯文本链接)标注来源于理科生网及本文完整链接,感谢!{alertInfo}

Ahmedabad
Kolkata
Hyderabad
后一页 Bangalore 前一页

Random Manga

Ads

نموذج الاتصال