50.C++多线程
约 258 字小于 1 分钟
重要方法
join(); 主线程等待子线程执行完毕
detach(); 让线程独立运行,主线程不等待它
joinable(); 检查线程是否可 join
this_thread::get_id()
this_thread::sleep_for(100ms);
this_thread::sleep_until(chrono::system_clock::now() + 100ms);
创建线程的方式
1.使用 std::thread(C++11 标准线程库)✅ 无返回值
2.使用 std::async(异步任务)✅ 有返回值 ( 异步任务 )
=====
3.使用 POSIX 线程(pthread,Linux 专用)
4.使用 Windows 线程(CreateThread,Windows 专用)
创建线程
1.使用 std::thread(C++11 标准库线程)
#include <iostream>
#include <thread>
using namespace std;
void runFn(int& arg, string argName)
{
cout << "参数1: " << arg << " 参数2:" << argName << endl;
arg = arg + 1;
}
int main()
{
int age = 123;
// 创建一个线程
thread t1(runFn, ref(age), "创建一个线程");
cout << " age: " << age<<endl;
// t1 加入主线程 阻塞主线程
t1.join();
cout << " age: " << age<<endl;
cout << "结束" << endl;
return 0;
}
2.使用 std::async(异步任务)
#include <iostream>
#include <future>
using namespace std;
int asyncFunction() {
return 42;
}
int main() {
future<int> result = async(launch::async, asyncFunction);
cout << "Result: " << result.get() << endl; // 获取线程返回值
return 0;
}