在现代软件开发中,C++多线程编程已成为提升程序性能和响应能力的关键技术。无论是处理大量数据、实现高性能服务器,还是开发交互式图形界面,掌握多线程同步机制都至关重要。本教程专为编程小白设计,将带你一步步理解 C++ 中的多线程基础,并通过简单示例快速上手。
线程是操作系统能够调度的最小执行单元。一个进程可以包含多个线程,它们共享进程的内存空间(如全局变量、堆等),但各自拥有独立的栈。多线程允许程序“同时”执行多个任务,从而提高效率。
自 C++11 起,标准库引入了 <thread> 头文件,使开发者无需依赖平台特定 API 即可创建和管理线程。这是学习 std::thread教程 的起点。
下面是一个最简单的多线程程序:
#include <iostream>#include <thread>void hello() { std::cout << "Hello from thread!\n";}int main() { std::thread t(hello); // 创建新线程,执行 hello 函数 t.join(); // 等待线程结束 std::cout << "Main thread continues.\n"; return 0;} 在这个例子中,std::thread t(hello) 启动了一个新线程来运行 hello() 函数。调用 t.join() 会阻塞主线程,直到子线程完成。如果不调用 join() 或 detach(),程序会在 std::thread 对象销毁时调用 std::terminate(),导致崩溃!
你可以像普通函数一样给线程函数传参:
#include <iostream>#include <thread>void print_message(const std::string& msg, int id) { std::cout << "Thread " << id << ": " << msg << "\n";}int main() { std::thread t1(print_message, "Hello", 1); std::thread t2(print_message, "World", 2); t1.join(); t2.join(); return 0;} 当多个线程访问共享资源(如全局变量)时,若不加控制,会导致数据竞争(Data Race),结果不可预测。为此,C++ 提供了多种多线程同步机制,如互斥锁(mutex)、条件变量等。
#include <iostream>#include <thread>#include <mutex>int counter = 0;std::mutex mtx; // 互斥锁void increment(int n) { for (int i = 0; i < n; ++i) { mtx.lock(); ++counter; mtx.unlock(); }}int main() { std::thread t1(increment, 100000); std::thread t2(increment, 100000); t1.join(); t2.join(); std::cout << "Final counter value: " << counter << "\n"; return 0;} 更安全的做法是使用 std::lock_guard,它利用 RAII 机制自动加锁/解锁:
void increment(int n) { for (int i = 0; i < n; ++i) { std::lock_guard<std::mutex> lock(mtx); ++counter; // lock 自动析构时释放 mutex }} 通过本教程,你已经掌握了:
std::thread 创建线程std::mutexstd::lock_guard)记住,C++并发入门只是第一步。后续你还可以学习条件变量(std::condition_variable)、原子操作(std::atomic)、线程池等高级主题。多练习、多调试,你将逐步成为多线程编程高手!
提示:编译多线程程序时,请链接 pthread 库(Linux/macOS): g++ -std=c++11 -pthread your_file.cpp
本文由主机测评网于2025-12-13发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025127327.html