MST

星途 面试题库

面试题:C++指针函数返回值与多线程环境下的资源管理

在多线程环境下,编写一个C++指针函数,该函数从共享资源(如共享内存块)中获取数据,并返回指向处理后数据的指针。函数需要考虑线程安全问题,防止数据竞争。同时,要合理处理返回指针指向的内存,确保在多线程环境下不会出现内存泄漏或悬空指针。描述你设计的同步机制,并在主函数中通过多线程调用展示该指针函数的正确性和安全性。
13.4万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

std::mutex sharedResourceMutex;
std::unique_ptr<int> sharedResource;

// 初始化共享资源
void initializeSharedResource() {
    sharedResource.reset(new int(42));
}

// 从共享资源获取数据并处理,返回指向处理后数据的指针
std::unique_ptr<int> getDataAndProcess() {
    std::lock_guard<std::mutex> lock(sharedResourceMutex);
    if (!sharedResource) {
        throw std::runtime_error("Shared resource not initialized");
    }
    // 这里简单地将数据翻倍作为处理
    int processedData = *sharedResource * 2;
    return std::make_unique<int>(processedData);
}

int main() {
    // 初始化共享资源
    initializeSharedResource();

    // 定义多个线程调用函数
    const int numThreads = 5;
    std::thread threads[numThreads];
    std::unique_ptr<int> results[numThreads];

    for (int i = 0; i < numThreads; ++i) {
        threads[i] = std::thread([&results, i]() {
            try {
                results[i] = getDataAndProcess();
            } catch (const std::exception& e) {
                std::cerr << "Exception in thread: " << e.what() << std::endl;
            }
        });
    }

    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }

    // 输出结果验证正确性
    for (int i = 0; i < numThreads; ++i) {
        if (results[i]) {
            std::cout << "Thread " << i << " result: " << *results[i] << std::endl;
        }
    }

    return 0;
}

同步机制描述

  1. 互斥锁(std::mutex:用于保护共享资源sharedResource。在访问共享资源前,通过std::lock_guard<std::mutex>来锁定互斥锁,这是一种RAII(Resource Acquisition Is Initialization)机制,在构造时锁定互斥锁,在析构时自动解锁,确保了即使函数因异常提前退出,互斥锁也能正确解锁,防止死锁。
  2. 智能指针(std::unique_ptr:用于管理动态分配的内存,避免内存泄漏。sharedResource使用std::unique_ptr<int>来管理共享资源的内存,getDataAndProcess函数返回std::unique_ptr<int>来管理处理后数据的内存。当std::unique_ptr离开其作用域时,会自动释放其所指向的内存,从而避免了悬空指针和内存泄漏问题。