2014-02-28 33 views
1

我從書上「C++在行動併發」下面的例子打字,但是它報告:C++ 11快速排序終止調用時沒有活動異常

"terminate called without an active exception". 

看來問題是與功能spawn_task,但我不知道什麼是錯的。

template<typename F, typename A> 
static std::future<typename std::result_of<F(A&&)>::type> spawn_task(F&& f, A&& a) 
{ 
    typedef typename std::result_of<F(A&&)>::type result_type; 
    std::packaged_task<result_type(A&&)> task(std::move(f)); 
    std::future<result_type> res(task.get_future()); 
    std::thread(std::move(task), std::move(a)); 
    return res; 
} 
template<typename T> 
static std::list<T> parallel_quick_sort(std::list<T> input) 
{ 
    if (input.empty()) 
    { 
     return input; 
    } 

    std::list<T> result; 
    result.splice(result.begin(), input, input.begin()); 
    T const& partition_val = *result.begin(); 
    typename std::list<T>::iterator divide_point = std::partition(
      input.begin(), input.end(), [&](T const& t) 
      { return t<partition_val;}); 
    std::list<T> lower_part; 
    lower_part.splice(lower_part.end(), input, input.begin(), divide_point); 


    std::future<std::list<T> > new_lower(
      spawn_task(&parallel_quick_sort<T>, std::move(lower_part))); 

    std::list<T> new_higher(parallel_quick_sort(std::move(input))); 
    result.splice(result.end(), new_higher); 
    result.splice(result.begin(), new_lower.get()); 
    return result; 

} 



static void test() 
{ 
    std::list<int> toSort={1,4,3,6,4,89,3}; 
    std::for_each(std::begin(toSort), std::end(toSort), [](int n){ std::cout << n << std::endl;}); 
    std::list<int> sorted; 
    sorted=parallel_quick_sort(toSort); 
    std::for_each(std::begin(sorted), std::end(sorted), [](int n){ std::cout << n << std::endl;}); 
} 

任何人都可以幫助我嗎?

回答

3

錯誤..我在谷歌的一些研究後,我想出了它。

我固定的代碼如下:

template<typename F, typename A> 
static std::future<typename std::result_of<F(A&&)>::type> spawn_task(F&& f, A&& a) 
{ 
    typedef typename std::result_of<F(A&&)>::type result_type; 
    std::packaged_task<result_type(A&&)> task(std::move(f)); 
    std::future<result_type> res(task.get_future()); 
    std::thread myThread(std::move(task), std::move(a)); 
    myThread.detach(); 
    return res; 
} 

發出錯誤消息,指出我有沒有加入線程。所以我應該加入或脫離。所以我按照上述做了。