2013-11-21 138 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; 
}