我正在將多線程中值函數作爲大型項目的一部分工作。我有一點C++經驗。下面的中值函數應該採用3維向量的向量,並返回一個3維向量,其中每個條目是輸入向量中該索引中所有條目的中值。所以如果輸入是< < 3,2,1>,< 1,2,3>,< 2,2,2 >>,則返回< 2,2,2>。該代碼將用於實現實時視頻中的中值模糊,因此希望對其進行多線程處理。C++ 11線程:將向量傳遞給線程函數時出錯
#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();
}
}
我遇到的問題是,在編譯時,G ++(和鐺也)給出一個相當難以理解的錯誤:
g++ -std=c++11 -pthread -o median median.cpp
In file included from /usr/include/c++/4.8.2/thread:39:0,
from median.cpp:1:
/usr/include/c++/4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::vector<int>, std::vector<std::vector<int> >, int))(std::vector<int>&, const std::vector<std::vector<int> >&, int)>’:
/usr/include/c++/4.8.2/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<int>&, const std::vector<std::vector<int> >&, int); _Args = {std::vector<int, std::allocator<int> >&, const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&, int}]’
median.cpp:15:58: required from here
/usr/include/c++/4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<int>, std::vector<std::vector<int> >, int)) (std::vector<int>&, const std::vector<std::vector<int> >&, int)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.8.2/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<int>, std::vector<std::vector<int> >, int)) (std::vector<int>&, const std::vector<std::vector<int> >&, int)>’
_M_invoke(_Index_tuple<_Indices...>)
^
我已發現類似的錯誤消息c++11 Thread class how to use a class member function,但它不會特別處理我的問題。 任何幫助將不勝感激,我完全期待這是因爲我不知道我在做什麼:P
編輯:線程函數和中位數的原型包含在頭文件median.h中。
當你得到這個編譯您有一個更狡猾的問題:你的'bgrPixel'向量不包含三個項目,所以當你做'bgrPixel [channel] = ...'你有[*未定義的行爲*](http://en.wikipedia.org/wiki/Undefined_behavior)。這可以很容易地通過說聲明矢量有三個項目解決:'std :: vector bgrPixel(3);' –
由於您的向量的大小爲3,您可以用'std'替換'std :: vector' :: array '。這將不太容易出錯。我沒有g ++編譯器,但它可以很好地適用於VC++。可能你的編譯器有問題。 –
謝謝! – chaffdog