c++中如何使用std::thread创建多线程程序_c++多线程创建与同步示例

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

c++中如何使用std::thread创建多线程程序_c++多线程创建与同步示例

在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; } 

说明:

立即进入豆包AI人工智官网入口”;

立即学习豆包AI人工智能在线问答入口”;

  • 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;只有引用类型才需要。

c++中如何使用std::thread创建多线程程序_c++多线程创建与同步示例

豆包AI编程

豆包推出的AI编程助手

c++中如何使用std::thread创建多线程程序_c++多线程创建与同步示例483

查看详情 c++中如何使用std::thread创建多线程程序_c++多线程创建与同步示例

使用lambda表达式创建线程

Lambda让线程代码更灵活,尤其适合短小逻辑。

 #include <iostream> #include <thread>  int main() {     auto task = []() {         std::cout << "Lambda thread running." << std::endl;     };      std::thread t(task);     t.join();     return 0; } 

线程同步:使用互斥锁(mutex)

多个线程访问共享数据时,需防止竞争条件。常用std::mutexstd::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; } 

说明:

立即进入豆包AI人工智官网入口”;

立即学习豆包AI人工智能在线问答入口”;

  • std::lock_guard在构造时加锁,析构时自动释放,避免死锁。
  • 即使函数抛出异常,也能保证锁被释放。

基本上就这些。掌握std::thread、参数传递和std::mutex后,就能写出基本的安全多线程程序。实际开发中还可结合std::atomicstd::condition_variable工具实现更复杂的同步逻辑。

上一篇
下一篇
text=ZqhQzanResources