#include <iostream>
#include <thread>
#include <mutex>
// 定义一个全局变量,多个线程将尝试同时访问它
int global_counter = 0;
// 定义一个互斥锁,用于保护对全局变量的访问
std::mutex counter_mutex;
void increment_counter(int thread_id) {
for (int i = 0; i < 1000; ++i) {
// 加锁,确保只有一个线程可以修改global_counter
std::lock_guard<std::mutex> lock(counter_mutex);
++global_counter;
// 解锁是自动的,当lock_guard对象离开作用域时会自动解锁
// 打印当前线程ID和计数器值(可选)
if (i % 100 == 0) {
std::cout << "Thread " << thread_id << " increments counter to " << global_counter << std::endl;
}
}
}
int main() {
// 创建两个线程,它们将并发地增加global_counter
std::thread t1(increment_counter, 1);
std::thread t2(increment_counter, 2);
// 等待两个线程完成
t1.join();
t2.join();
// 打印最终的计数器值
std::cout << "Final counter value: " << global_counter << std::endl;
return 0;
}
全局变量 global_counter
:
互斥锁 counter_mutex
:
global_counter
导致数据竞争问题。函数 increment_counter
:
global_counter
的值。std::lock_guard<std::mutex>
来自动管理锁的获取和释放,确保在临界区内的代码只被一个线程执行。主函数 main
:
t1
和 t2
,它们分别调用 increment_counter
函数。join
方法等待两个线程完成。global_counter
的最终值。通过这种方式,我们可以确保多个线程安全地访问和修改共享资源,避免了数据竞争和不一致的问题。
上一篇:c++ 遍历vector
下一篇:auto在c++中的作用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站