C++中多线程编程依赖<thread>头文件,通过std::thread创建线程,结合std::mutex和std::lock_guard实现同步,确保共享数据安全,示例包括函数、lambda和成员函数的线程化使用,并强调资源管理和避免竞态条件。

在C++中创建和管理多线程程序主要依赖于标准库中的 <thread> 头文件,从 C++11 开始原生支持多线程编程。通过 std::thread 可以轻松启动新线程,并结合 std::mutex、std::lock_guard 等工具进行资源保护和同步操作。
要创建一个线程,只需实例化一个 std::thread 对象,并传入一个可调用的目标(函数、lambda 表达式或函数对象)。
示例代码:
#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: " << std::this_thread::get_id() << std::endl;
t.join(); // 等待线程完成
return 0;
}
除了普通函数,还可以用 lambda 表达式或绑定类成员函数来创建线程,提升灵活性。
立即学习“C++免费学习笔记(深入)”;
示例:使用 lambda 和成员函数
#include <iostream>
#include <thread>
struct Task {
void run(int id) {
std::cout << "Task " << id << " running on thread "
<< std::this_thread::get_id() << std::endl;
}
};
int main() {
Task t;
// 使用 lambda
std::thread t1([](){
for(int i = 0; i < 3; ++i) {
std::cout << "Lambda loop " << i << std::endl;
}
});
// 调用成员函数
std::thread t2(&Task::run, &t, 42);
t1.join();
t2.join();
return 0;
}
多个线程访问共享数据时容易引发竞争条件。使用 std::mutex 加锁可以避免数据冲突。
示例:保护共享变量
#include <iostream>
#include <thread>
#include <mutex>
int counter = 0;
std::mutex mtx;
void increment() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
++counter;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Final counter value: " << counter << std::endl;
return 0;
}
合理管理线程生命周期和资源是编写稳定多线程程序的关键。
基本上就这些。C++ 多线程编程并不复杂,但需要注意同步和资源管理细节,才能写出高效又安全的并发程序。
以上就是c++++怎么创建一个多线程程序_c++多线程程序创建与管理方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号