C++中线程安全的vector

529 阅读1分钟

C++标准库中并没有提供专门的线程安全的vector实现。然而,你可以通过使用互斥锁(mutex)来保护vector,以确保在多线程环境下的安全访问。

以下是一个简单的示例,演示了如何使用互斥锁保护vector

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

std::vector<int> sharedVector;
std::mutex mtx;

void addToVector(int value) {
    std::lock_guard<std::mutex> lock(mtx); // 使用互斥锁保护共享的vector
    sharedVector.push_back(value);
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 10; ++i) {
        threads.push_back(std::thread(addToVector, i));
    }

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

    // 输出共享的vector内容
    for (int value : sharedVector) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    return 0;
}

在上面的示例中,std::mutex用于保护sharedVector,在向sharedVector添加元素时,线程首先获得互斥锁(通过std::lock_guard),以确保只有一个线程可以修改sharedVector,从而避免竞争条件和数据竞争。

虽然这种方法可以确保vector在多线程环境下的安全访问,但需要注意锁的使用可能会影响程序的性能。因此,在实际应用中,你需要根据具体情况综合考虑性能和线程安全性。