2013-11-21 87 views
1

如何获取发送到std :: threads的函数的返回值? 我正在开发一个函数,它可以在一个彩色/多光谱图像的每个通道中创建一个过滤器,创建为2d图像。但之前在这个库中实现的许多函数都有一个图像作为返回,我试图创建一个函数,它将返回的图像作为参数,但它不起作用。以下是该代码的副本:std ::非void函数的线程(C++ 11)

template< class D, class A > 
    template < typename... Args> 
    void Image < D, A >::VoidFunction(Image< D, A > &out, Image < D, A > function (const Image< D, A >& , Args ...), 
        const Image <D, A > &in, Args... args) { 
    out = (function) (in, args...); 
    return ; 
    } 

    template< class D, class A > 
    template < typename... Args> 
    Image < D, A > Image < D, A >::multiSpecImgFilter(Image < D, A > function (const Image<D, A>& , Args ...), 
          const Image <D, A > &img, Args... args) { 
    if (img.Dims() != 3) { 
     std::string msg(std::string(__FILE__) + ": " + std::to_string(__LINE__) + ": Image<D,A> " + "::" + 
       std::string(__FUNCTION__) + ": error: Image channels must have 2 dimensions"); 
     throw(std::logic_error(msg)); 
    } 
    std::vector< Image < D, A > > channel = img.Split(); 
    // std::vector<std::thread> threads ; 
    // for(size_t thd = 0; thd < channel.size(); ++thd) 
    // threads[ thd ].join(); 

    try { 
     for (int ch = 0; ch < channel.size() ; ch++) 
    std::thread thd (&VoidFunction, channel[ch], function, channel[ch], args...); 
    } 
    catch(...) { 
     for (int ch = 0; ch < img.size(2) ; ch++) 
     channel[ ch ] = (function) (channel [ ch ], args...); 
    } 
    return (Image< D, A >::Merge(channel, img.PixelSize().back(), img.Channel().back())); 
    } 
+2

我不确定我是否理解这个问题,但是如果我这样做,那么您可能会对'std :: packaged_task'和'std :: future'感兴趣。 –

+0

将您的函数打包到'std :: packaged_task'中,获取'future',将打包的任务移动到一个线程中。 – Zeta

+1

'std :: async'也可能是一种预先打包的异步函数调用。 – Yakk

回答

1

您可以使用lambda表达式并将结果存储在其中。

#include <iostream> 
#include <thread> 

int threadFunction() 
{ 
    return 8; 
} 


int main() 
{ 
    int retCode; 
    //retCode is captured by ref to be sure the modifs are also in the main thread 
    std::thread t([&retCode](){ 
     std::cout << "thread function\n"; 
     retCode=threadFunction(); 
    }); 
    std::cout << "main thread\n";//this will display 8 
    t.join();//to avoid a crash 
    return 0; 
}