MST

星途 面试题库

面试题:C++ 多线程编程中互斥与同步的基础区别

请阐述在C++多线程编程里,互斥(Mutex)和同步(Synchronization)概念上的主要区别。并举例说明在什么场景下你会优先选择使用互斥锁,什么场景下会优先考虑其他同步机制。
35.5万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

区别

  1. 定义
    • 互斥(Mutex):是一种特殊的二元信号量,用于保证在同一时刻只有一个线程能够访问共享资源,本质上是一种简单的同步工具,主要解决多线程竞争共享资源时的数据一致性问题。
    • 同步(Synchronization):是一个更广泛的概念,它涉及到协调多个线程的执行顺序,确保线程之间按照预定的顺序进行交互和操作,以避免竞争条件和数据不一致等问题。互斥是同步的一种手段。
  2. 侧重点
    • 互斥:侧重于保护共享资源,防止多个线程同时访问,从而造成数据混乱。比如多个线程同时对一个全局变量进行写操作,互斥锁可以保证同一时间只有一个线程能写。
    • 同步:更强调线程间的协作,确保线程按特定顺序执行。例如线程A要先完成某些初始化操作,线程B才能开始后续依赖这些初始化结果的操作。

应用场景

  1. 优先选择互斥锁的场景 当多个线程需要访问共享资源(如共享内存区域、全局变量等),且目的仅仅是防止数据竞争时,优先选择互斥锁。例如,一个银行账户类,多个线程可能同时对账户余额进行取款或存款操作。代码示例如下:
#include <iostream>
#include <mutex>
#include <thread>

class BankAccount {
public:
    BankAccount(int initialBalance) : balance(initialBalance) {}

    void deposit(int amount) {
        std::lock_guard<std::mutex> lock(mutex_);
        balance += amount;
        std::cout << "Deposited " << amount << ". New balance: " << balance << std::endl;
    }

    void withdraw(int amount) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (balance >= amount) {
            balance -= amount;
            std::cout << "Withdrew " << amount << ". New balance: " << balance << std::endl;
        } else {
            std::cout << "Insufficient funds." << std::endl;
        }
    }

private:
    int balance;
    std::mutex mutex_;
};

int main() {
    BankAccount account(1000);
    std::thread t1(&BankAccount::deposit, &account, 500);
    std::thread t2(&BankAccount::withdraw, &account, 300);

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

    return 0;
}

在这个例子中,std::mutex确保了depositwithdraw操作不会同时访问balance变量,避免数据竞争。 2. 优先考虑其他同步机制的场景 - 条件变量(Condition Variable):当线程需要在某个条件满足时才继续执行,而不是简单地访问共享资源。例如,生产者 - 消费者模型中,消费者线程需要等待生产者线程将数据放入缓冲区后才能消费。代码示例如下:

#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

std::queue<int> q;
std::mutex m;
std::condition_variable cv;
bool finished = false;

void producer() {
    for (int i = 0; i < 10; ++i) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::unique_lock<std::mutex> lock(m);
        q.push(i);
        std::cout << "Produced: " << i << std::endl;
        lock.unlock();
        cv.notify_one();
    }
    std::unique_lock<std::mutex> lock(m);
    finished = true;
    cv.notify_all();
}

void consumer() {
    while (true) {
        std::unique_lock<std::mutex> lock(m);
        cv.wait(lock, []{ return!q.empty() || finished; });
        if (q.empty() && finished) break;
        int data = q.front();
        q.pop();
        std::cout << "Consumed: " << data << std::endl;
    }
}

int main() {
    std::thread t1(producer);
    std::thread t2(consumer);

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

    return 0;
}
- **信号量(Semaphore)**:当需要限制同时访问共享资源的线程数量时,信号量更合适。例如,一个停车场管理系统,停车场有固定数量的车位,信号量可以用来控制进入停车场的车辆(线程)数量。
#include <iostream>
#include <thread>
#include <semaphore>

std::counting_semaphore<10> parkingLot(10);

void carEnter(int id) {
    parkingLot.acquire();
    std::cout << "Car " << id << " entered the parking lot." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Car " << id << " left the parking lot." << std::endl;
    parkingLot.release();
}

int main() {
    std::thread threads[20];
    for (int i = 0; i < 20; ++i) {
        threads[i] = std::thread(carEnter, i);
    }

    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}