MST

星途 面试题库

面试题:C++ 多线程中全局变量的竞争问题及解决方法

在C++多线程环境下,假设有一个全局变量`int globalVar = 0;`,多个线程对其进行自增操作。请指出这种情况下可能出现的问题,并描述至少一种解决该问题的方法,同时用代码示例说明。
22.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

可能出现的问题

在多线程环境下,对全局变量globalVar进行自增操作会出现竞态条件(Race Condition)问题。因为自增操作(globalVar++)并非原子操作,它通常包含读取变量值、增加1、写回变量值这几个步骤。当多个线程同时执行自增操作时,可能会出现一个线程读取了变量值后,还未写回,另一个线程又读取了相同的值,导致最终结果不正确。

解决方法

  1. 使用互斥锁(std::mutex:互斥锁可以保证在同一时间只有一个线程能够访问共享资源,从而避免竞态条件。
  2. 使用原子变量(std::atomic:C++11引入的std::atomic类型提供了原子操作,对其进行的操作都是原子的,不需要额外的同步机制。

代码示例

  1. 使用互斥锁
#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;
}
  1. 使用原子变量
#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;
}