C++中多线程通过std::thread实现,需调用join或detach;参数传递用std::ref引用;同步用std::mutex配合std::lock_guard防数据竞争。

在C++中使用多线程,主要依赖于标准库中的 std::thread,从C++11开始引入,使得多线程编程变得简单且跨平台。下面介绍如何创建和管理线程、传递参数、同步操作以及常见注意事项。
使用 std::thread 可以轻松启动一个新线程。只需将函数名或可调用对象传入线程构造函数。
示例:
#include <iostream>
#include <thread>
void say_hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(say_hello); // 启动线程
t.join(); // 等待线程结束
return 0;
}
注意:必须调用 join() 或 detach(),否则程序会终止。
立即学习“C++免费学习笔记(深入)”;
可以向线程函数传递参数,但需注意默认是值传递。若要传引用,需使用 std::ref。
示例:
#include <iostream>
#include <thread>
void print_number(int& n) {
n = 42;
}
int main() {
int num = 0;
std::thread t(print_number, std::ref(num)); // 引用传递
t.join();
std::cout << "num is now: " << num << std::endl; // 输出 42
return 0;
}
多个线程访问共享数据时,需要防止数据竞争。常用 std::mutex 加锁保护。
示例:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void safe_print(int id) {
mtx.lock();
std::cout << "Thread " << id << " is printing." << std::endl;
mtx.unlock();
}
更推荐使用 std::lock_guard 实现自动加锁解锁:
void safe_print(int id) {
std::lock_guard<std::mutex> guard(mtx);
std::cout << "Thread " << id << " is printing." << std::endl;
}
lambda 让线程逻辑更灵活,适合短期任务。
std::thread t([](){
std::cout << "Lambda thread running." << std::endl;
});
t.join();
基本上就这些。掌握 thread、mutex 和 lock_guard 就能处理大多数多线程场景。注意避免死锁、确保资源正确释放,多线程程序就能稳定运行。
以上就是C++如何使用多线程_C++ 多线程使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号