gpt4 book ai didi

C++11 quicksort terminate 在没有事件异常的情况下被调用

转载 作者:行者123 更新时间:2023-11-30 02:48:19 25 4
gpt4 key购买 nike

我输入了“C++ 并发实战”一书中的以下示例,但它报告:

"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;});
}

谁能帮我解决这个问题?

最佳答案

呃..我在谷歌上做了一些研究后发现了。

我修改了如下代码:

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;
}

错误消息指出我有未加入的线程。所以我应该加入或分离。所以我按照上面的方法做了。

关于C++11 quicksort terminate 在没有事件异常的情况下被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22095073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com