MST
星途 面试题库

面试题:C++多线程中的锁机制

在C++多线程编程中,常见的锁有互斥锁(mutex)、读写锁(read - write lock)等。请描述互斥锁和读写锁的适用场景,并举例说明如何在代码中使用它们来保护共享资源。
47.0万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

互斥锁适用场景

互斥锁适用于当共享资源需要被独占访问的场景,即同一时间只允许一个线程对共享资源进行读写操作,以防止数据竞争和不一致。比如多个线程同时访问和修改一个全局变量时,就需要互斥锁来保证数据的一致性。

读写锁适用场景

读写锁适用于读操作远多于写操作的场景。读操作之间不会产生数据竞争,所以可以允许多个线程同时进行读操作。而写操作则需要独占资源,以避免数据不一致。例如,一个数据库的查询(读操作)频繁,而更新(写操作)较少的场景就适合使用读写锁。

互斥锁代码示例

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int sharedVariable = 0;

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

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

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

    std::cout << "Final value of sharedVariable: " << sharedVariable << std::endl;
    return 0;
}

读写锁代码示例(以C++17的std::shared_mutex为例)

#include <iostream>
#include <thread>
#include <shared_mutex>
#include <vector>

std::shared_mutex rwMutex;
int sharedData = 0;

void readData(int id) {
    rwMutex.lock_shared();
    std::cout << "Thread " << id << " reads data: " << sharedData << std::endl;
    rwMutex.unlock_shared();
}

void writeData(int id) {
    rwMutex.lock();
    ++sharedData;
    std::cout << "Thread " << id << " writes data: " << sharedData << std::endl;
    rwMutex.unlock();
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 3; ++i) {
        if (i % 2 == 0) {
            threads.emplace_back(readData, i);
        } else {
            threads.emplace_back(writeData, i);
        }
    }

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

    return 0;
}