面试题答案
一键面试可能出现的问题
在多线程环境下,对全局变量globalVar
进行自增操作会出现竞态条件(Race Condition)问题。因为自增操作(globalVar++
)并非原子操作,它通常包含读取变量值、增加1、写回变量值这几个步骤。当多个线程同时执行自增操作时,可能会出现一个线程读取了变量值后,还未写回,另一个线程又读取了相同的值,导致最终结果不正确。
解决方法
- 使用互斥锁(
std::mutex
):互斥锁可以保证在同一时间只有一个线程能够访问共享资源,从而避免竞态条件。 - 使用原子变量(
std::atomic
):C++11引入的std::atomic
类型提供了原子操作,对其进行的操作都是原子的,不需要额外的同步机制。
代码示例
- 使用互斥锁
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int globalVar = 0;
void increment() {
for (int i = 0; i < 10000; ++i) {
mtx.lock();
globalVar++;
mtx.unlock();
}
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(increment);
}
for (auto& th : threads) {
th.join();
}
std::cout << "Final value of globalVar: " << globalVar << std::endl;
return 0;
}
- 使用原子变量
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> globalVar(0);
void increment() {
for (int i = 0; i < 10000; ++i) {
globalVar++;
}
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(increment);
}
for (auto& th : threads) {
th.join();
}
std::cout << "Final value of globalVar: " << globalVar << std::endl;
return 0;
}