欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 多线程编程:std::thread 与同步机制

时间:2026年08月12日 04:46:50 浏览:1

创建线程


#include <thread>
#include <iostream>

void task(int id) {
std::cout << "Thread " << id << " running" << std::endl;
}

int main() {
std::thread t1(task, 1);
std::thread t2([](int x) { std::cout << x << std::endl; }, 2);

t1.join(); // 等待线程结束
t2.join();
return 0;
}

互斥锁 std::mutex


#include <mutex>
std::mutex mtx;
int counter = 0;

void increment() {
std::lock_guard<std::mutex> lock(mtx); // RAII 自动解锁
counter++;
}

条件变量 std::condition_variable


用于线程间事件通知。


std::condition_variable cv;
bool ready = false;

// 等待线程
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; });

// 通知线程
ready = true;
cv.notify_one();

原子操作 std::atomic


对于简单的计数,用原子变量比互斥锁更高效。


std::atomic<int> counter(0);
counter.fetch_add(1, std::memory_order_relaxed);

多线程编程务必注意死锁和数据竞争,善用 RAII 管理锁。