packaged_task and future

In the code example below, everything "looks" fine, but why do I get a runtime Debug error: abort() has been called, please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <future>
#include <vector>
#include <numeric>

double accum(double* beg, double* end, double init)
// compute the sum of [beg:end) starting with the initial
//value init
{
	return std::accumulate(beg, end, init);
}

double comp2(std::vector<double>& v)
{
	using Task_type = double(double*, double*, double); // type of task

	std::packaged_task<Task_type> pt0{ accum };
	// package the task (i.e., accum)

	std::packaged_task<Task_type> pt1{ accum };
	std::future<double> f0{ pt0.get_future() };
	// get hold of pt0's future

	std::future<double> f1{ pt1.get_future() };
	// get hold of pt1's future

	double* first = &v[0];
	std::thread t1{ move(pt0),first,first + v.size() / 2,0 };
	// start a thread for pt0

	std::thread t2{ move(pt1),first + v.size() / 2,first + v.size(),0 };
	// start a thread for pt1
	// ...

	return f0.get() + f1.get();
	// get the results
}

int main() {
	std::vector v{ 1.2, 2.2, 3.3, 4.4, 5.5, 6.6, 7.6, 8.8 };
	std::cout << comp2(v) << '\n';

	system("pause");
	return 0;
}

Windows, VS compiler.
Last edited on
You need to call detach() on your threads before they go out of scope.

https://en.cppreference.com/w/cpp/thread/thread/%7Ethread
If *this has an associated thread (joinable() == true), std::terminate() is called.
A thread object does not have an associated thread (and is safe to destroy) after
* it was default-constructed
* it was moved from
* join() has been called
* detach() has been called


You could also call join() here, but std::future::get() blocks anyway.

-Albatross
Thank you. :) I don't know why I'd forgot to call join there!
Both join and detach work there, why do you mean by "but std::future::get() blocks anyway", please?
Topic archived. No new replies allowed.