多线程编程
学习C++多线程编程的基础知识和实践应用
80%
线程基础
互斥锁
条件变量
线程的创建与管理
创建和使用线程
使用C++11标准线程库创建和管理线程。
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
// 线程函数
void threadFunction(int id) {
for(int i = 0; i < 3; i++) {
cout << "线程 " << id << " 执行中..." << endl;
this_thread::sleep_for(chrono::seconds(1));
}
}
int main() {
cout << "主线程开始" << endl;
// 创建线程
thread t1(threadFunction, 1);
thread t2(threadFunction, 2);
// 等待线程完成
t1.join();
t2.join();
cout << "所有线程已完成" << endl;
return 0;
}
// 使用Lambda表达式
void lambdaThread() {
auto lambda = [](int x) {
cout << "Lambda线程: " << x << endl;
};
thread t(lambda, 100);
t.join();
}
- 使用std::thread创建线程
- 线程函数可以是普通函数、Lambda表达式或函数对象
- join()等待线程完成
- detach()将线程与主线程分离