C++中实现多线程编程
一、基于POSIX线程库(pthreads)
适用场景:Linux/Unix系统、需要底层线程控制或兼容旧代码。
核心步骤:
-
包含头文件:
#include <pthread.h> -
定义线程函数:返回类型为
void*,参数为void*指针。 -
创建线程:使用
pthread_create函数。 -
等待线程结束:使用
pthread_join回收资源。
示例代码:
#include <iostream>
#include <pthread.h>void* threadFunction(void* arg) {int id = *((int*)arg);std::cout << "Thread " << id << " is running.\n";return nullptr;
}int main() {const int numThreads = 5;pthread_t threads[numThreads];int threadIds[numThreads];for (int i = 0; i < numThreads; ++i) {threadIds[i] = i;if (pthread_create(&threads[i], nullptr, threadFunction, &threadIds[i]) != 0) {