[cpp-threads] Thread API interface tweaks
Ion Gaztañaga
igaztanaga at gmail.com
Sun Aug 27 07:24:10 BST 2006
> Actually I think future<void> is quite useful, though I admit I'm mostly thinking of designs where the future<T> is both a future value (primarily) and a "handle" to the asynchronous operation that is responsible for generating the future value (not necessarily "thread").
In that case, the question is: are we going to use both thread and
future at the same time? If that's not the case we can just define
future taking a rvalue reference of "thread":
template<class T>
class future
{
future(thread<T> &&t);
};
This clearly states that the thread object (which was movable but not
copyable) is replaced with a more advanced (and expensive) type. This
constructor can just move heap allocated return value to a shared_ptr
to implement the reference counting semantics. This approach allows
having a "thread" object that can move the return value and a future
that returns copies of the value. Losing the capability to move the
return type in "thread" is a big handicap IMHO. "thread" would just
return the value once and it would be joinable from just one thread
(using pthread_join(), for example). So we can have these examples:
a) Correct code, futures are reference counted
future<int> f = launch_thread(...);
future<int> f2(f);
int result1 = f();
int result2 = f2();
//----------------------
b) Incorrect code, thread can be joined only once (and the value is moved)
thread<int> t = launch_thread(...);
int result1 = t();
//This throws
int result2 = t();
//----------------------
c) Incorrect code, future must take ownership of thread
thread<int> j = launch_thread(...);
//Compilation error
future<int> f(j);
//----------------------
d) Incorrect code, a future takes ownership of the thread and that
object is now empty
thread<int> j = launch_thread(...);
future<int> f(std::move(j));
//Trying to join an empty "thread" throws
int = j();
Now the question is if using both thread and future at the same time
as handles is a desirable feature.
Regards,
Ion
More information about the cpp-threads
mailing list