#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <atomic>
// 共享资源
std::atomic<int> shared_counter(0);
std::mutex mtx;
// 线程函数
void increment_counter(int id) {
for (int i = 0; i < 1000; ++i) {
// 使用锁保护共享资源
std::lock_guard<std::mutex> lock(mtx);
++shared_counter;
// 模拟一些工作
if (shared_counter % 100 == 0) {
std::cout << "Thread " << id << " incremented counter to " << shared_counter << std::endl;
}
}
}
int main() {
const int num_threads = 10;
std::vector<std::thread> threads;
// 创建多个线程
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back(increment_counter, i);
}
// 等待所有线程完成
for (auto& t : threads) {
t.join();
}
std::cout << "Final counter value: " << shared_counter << std::endl;
return 0;
}
std::atomic<int> shared_counter(0);:使用 std::atomic 来确保对 shared_counter 的访问是原子操作,避免竞态条件。std::mutex mtx;:定义一个互斥锁,用于保护共享资源。increment_counter 函数:每个线程执行的函数,负责递增共享计数器。为了确保线程安全,使用了 std::lock_guard 来自动管理锁的获取和释放。main 函数:创建多个线程,并等待它们完成。每个线程都会调用 increment_counter 函数来递增共享计数器。这段代码展示了如何在 C++ 中实现高并发编程,通过使用多线程和同步机制(如互斥锁和原子操作)来确保线程安全。
上一篇:c和c++
下一篇:c++获取当前时间
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站