小编Hoo*_*oon的帖子

多个线程在同一个向量的不同向量上并发添加元素发生错误

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

struct A {
    std::vector<int> a;
};

struct B{
    std::vector<A> b;
    std::mutex mtx;
};

void work(int id, struct B& b) {
    std::unique_lock<std::mutex> lck(b.mtx);

    b.b.push_back(A());
    struct A& a = b.b.back();

    lck.unlock();

    for(int i = 0; i < 1000; i++) {
        std::cout << id << " " << i << std::endl;
        a.a.push_back(i);
    }
}

int main() {
    struct B b;
    std::thread t1, t2;

    t1 = std::thread([&] {
        work(1, b);
    });

    t2 = std::thread([&] {
        work(2, …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading vector

5
推荐指数
1
解决办法
63
查看次数

标签 统计

c++ ×1

multithreading ×1

vector ×1