template <class T> int
ACE_Future_Rep<T>::set (const T &r,
ACE_Future<T> &caller)
{
// If the value is already produced, ignore it...
if (this->value_ == 0)
{
ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX,
ace_mon,
this->value_ready_mutex_,
-1);
// Otherwise, create a new result value. Note the use of the
// Double-checked locking pattern to avoid multiple allocations.
if (this->value_ == 0) // Still no value, so proceed
{
ACE_NEW_RETURN (this->value_,
T (r),
-1);
// Remove and notify all subscribed observers.
typename OBSERVER_COLLECTION::iterator iterator =
this->observer_collection_.begin ();
typename OBSERVER_COLLECTION::iterator end =
this->observer_collection_.end ();
while (iterator != end)
{
OBSERVER *observer = *iterator++;
observer->update (caller);
}
// Signal all the waiting threads.
return this->value_ready_.broadcast ();
}
// Destructor releases the lock.
}
return 0;
}
只使用一次的原因是为了客户端可以确认,当前返回值是那一次功能调用的返回值。
举例,客户端触发了两次调用, 然后因某种原因只收到一次回复结果, 如果充许多次复写结果,那此时就搞不清,到底该回复是指那次调用结果的回复。
如果采用参数来区分, 又使问题复杂化,例如参数之间怎么做到不重复ID。
所以直接只充许使用一次是最快最简单的方法。
主动对象的好处: 在主动对象模式里, 执行功能不是在调用者处执行, 而是在被调用者处执行并且被调用者会在内部又消息的方式串行这些调用,从而解决多个调用者的并发调用对象功能的问题。