MST

星途 面试题库

面试题:C++多线程编程中互斥锁的基础应用

在C++多线程环境下,假设有两个线程需要访问并修改同一个共享变量,用代码示例展示如何使用互斥锁来确保数据的一致性。请使用C++标准库中的<mutex>。
50.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int sharedVariable = 0;

void increment() {
    for (int i = 0; i < 1000000; ++i) {
        mtx.lock();
        ++sharedVariable;
        mtx.unlock();
    }
}

void decrement() {
    for (int i = 0; i < 1000000; ++i) {
        mtx.lock();
        --sharedVariable;
        mtx.unlock();
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(decrement);

    t1.join();
    t2.join();

    std::cout << "Final value of shared variable: " << sharedVariable << std::endl;

    return 0;
}

在上述代码中:

  1. 引入了<iostream>用于输出,<thread>用于多线程编程,<mutex>用于使用互斥锁。
  2. 定义了一个全局互斥锁mtx和共享变量sharedVariable
  3. increment函数和decrement函数分别对共享变量进行增加和减少操作,在操作前后通过mtx.lock()mtx.unlock()来锁定和解锁互斥锁,确保同一时间只有一个线程能访问和修改共享变量,从而保证数据一致性。
  4. main函数中创建并启动两个线程,一个执行increment,一个执行decrement,最后等待两个线程执行完毕并输出共享变量的最终值。