小编Hus*_*mov的帖子

在 C++ 中将 Mutex 和 lock_guard 与向量一起使用

我是 C++ 线程的新手。我需要您有关mutexand的使用的帮助lock_guard(这部分并不重要)。我有一个主要功能和一个次要功能。

lock_guard(mtx)请告诉我为什么当我添加;时多线程不起作用 当我删除它时,它运行得更快但错误。你能帮我吗?

我需要正确访问向量vec并启用线程。

#include <vector>
#include <thread>

std::mutex mtx;

void threadCall(std::vector<int> &vec, int start, int end){
    std::lock_guard<std::mutex> guard(mtx);
    for(int i=start; i<end; i++)
      vec[i] = i;
}

void ThreadFunc(std::vector<int> vec){
    std::vector<std::thread> threads(2);
    threads[0] = std::thread(&threadCall, std::ref(vec), 0, 10);
    threads[1] = std::thread(&threadCall, std::ref(vec), 10, 20);

    threads[0].join();
    threads[1].join();
}

int main(){

    std::vector<int> vec(20);
    ThreadFunc(vec);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ multithreading c++11

1
推荐指数
2
解决办法
6921
查看次数

标签 统计

c++ ×1

c++11 ×1

multithreading ×1