C++ C++;11线程:向线程函数传递向量时出错

C++ C++;11线程:向线程函数传递向量时出错,c++,multithreading,c++11,stdthread,C++,Multithreading,C++11,Stdthread,作为一个更大项目的一部分,我正在研究一个多线程中值函数。我有很少的C++经验。下面的中值函数应取一个三维int向量向量,并返回一个三维int向量,其中每个条目是输入向量中该索引中所有条目的中值。因此,如果输入为,则返回为。这段代码将用于实现实时视频中的中值模糊,因此希望对其进行多线程处理 #include <thread> #include <iostream> #include <mutex> #include <vector> #include

作为一个更大项目的一部分,我正在研究一个多线程中值函数。我有很少的C++经验。下面的中值函数应取一个三维int向量向量,并返回一个三维int向量,其中每个条目是输入向量中该索引中所有条目的中值。因此,如果输入为,则返回为。这段代码将用于实现实时视频中的中值模糊,因此希望对其进行多线程处理

#include <thread>
#include <iostream>
#include <mutex>
#include <vector>
#include <algorithm>
#include "median.h"

// mutex to protect bgrPixel (possibly not needed)
std::mutex mtx;


std::vector<int> median(const std::vector<std::vector<int> >& input)
{
    std::vector<int> bgrPixel;              // Vector to store median BGR value
    std::thread first(thread_function, bgrPixel, input, 0); // thread for each colour channel
    std::thread second(thread_function, bgrPixel, input, 1);
    std::thread third(thread_function, bgrPixel, input, 2);
    first.join();
    second.join();
    third.join(); 
    return bgrPixel;
}

void thread_function(std::vector<int>& bgrPixel, const std::vector<std::vector<int> >&                 input1, int channel)
{

    std::vector<int> input = input1[channel];  // copy the colour channel
    std::sort(input.begin(), input.end());
    int size = input.size();
    if (size %2 == 0)   // get the median
    {
        mtx.lock();
        bgrPixel[channel] = (input[size/2] + input[size/2 + 1])/2;
        mtx.unlock();
    } else
    {
        mtx.lock();
        bgrPixel[channel] = input[(size-1)/2];
        mtx.unlock();
    }
}
#包括
#包括
#包括
#包括
#包括,但它没有具体处理我的问题。
任何帮助都将不胜感激,我完全希望这是因为我不知道我在做什么:P

编辑:线程函数和中间值的原型包含在头文件median.h中。

替换

std::thread first(thread_function, bgrPixel, input, 0);


活生生的例子:

当你编译这个时,你会遇到一个更棘手的问题:你的
bgrPixel
向量不包含三项,所以当你执行
bgrPixel[channel]=…
时,你就有了。这可以很容易地通过声明向量有三个项来解决:
std::vector bgrPixel(3)
由于向量的大小为3,因此可以将
std::vector
替换为
std::array
。这样就不那么容易出错。我没有g++编译器,但它与VC++配合得很好。您的编译器可能有问题。您不需要互斥锁来防止同时访问
bgrPixel
:每个线程访问一个不同的元素-
通道
每个线程都是不同的-并且对不同容器元素的访问是不冲突的。谢谢!那太好了!我还发现,如果我根本不使用引用,它将被编译。我需要阅读参考文献。测试过,当主线程认为变量不必要时,它可能会被删除,您可能会阅读一些“随机”信息,而不是您所期望的。所以我想如果你真的不需要的话,最好不要通过引用。
std::thread first(thread_function, bgrPixel, input, 0);
std::thread first(thread_function, std::ref(bgrPixel), std::ref(input), 0);