C++中使用std::thread可直接创建多线程,通过函数、lambda或可调用对象启动线程,支持参数传递(引用需用std::ref),并可用std::mutex和std::lock_guard实现线程同步,确保共享数据安全。

在C++中使用std::thread创建多线程程序非常直接。从C++11开始,标准库提供了<thread>头文件,支持跨平台的多线程编程。下面介绍如何创建线程、传递参数、以及简单的线程同步方法。
要启动一个新线程,只需将函数名或可调用对象传入std::thread构造函数。
示例:
#include <iostream>
#include <thread>
void say_hello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread t(say_hello); // 启动线程
std::cout << "Main thread running." << std::endl;
t.join(); // 等待线程结束
return 0;
}
说明:
立即学习“C++免费学习笔记(深入)”;
t.join() 表示主线程等待子线程执行完毕。join()或detach(),程序在thread对象析构时会调用std::terminate()终止程序。可以通过额外参数将数据传入线程函数。注意:默认是按值传递,若需引用,必须使用std::ref。
#include <iostream>
#include <thread>
void print_number(int& n) {
n += 10;
std::cout << "Thread: n = " << n << std::endl;
}
int main() {
int num = 5;
std::thread t(print_number, std::ref(num)); // 使用std::ref传引用
t.join();
std::cout << "Main: num = " << num << std::endl; // 输出15
return 0;
}
注意:如果传指针或值,不需要std::ref;只有引用类型才需要。
Lambda让线程代码更灵活,尤其适合短小逻辑。
#include <iostream>
#include <thread>
int main() {
auto task = []() {
std::cout << "Lambda thread running." << std::endl;
};
std::thread t(task);
t.join();
return 0;
}
多个线程访问共享数据时,需防止竞争条件。常用std::mutex和std::lock_guard保护临界区。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int shared_counter = 0;
void increment() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx); // 自动加锁/解锁
++shared_counter;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Final counter value: " << shared_counter << std::endl;
return 0;
}
说明:
立即学习“C++免费学习笔记(深入)”;
std::lock_guard在构造时加锁,析构时自动释放,避免死锁。基本上就这些。掌握std::thread、参数传递和std::mutex后,就能写出基本的安全多线程程序。实际开发中还可结合std::atomic、std::condition_variable等工具实现更复杂的同步逻辑。
以上就是c++++中如何使用std::thread创建多线程程序_c++多线程创建与同步示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号