Libprocess concepts

先看官方定义:

1
Library that provides an actor style message-passing programming model (in C++).

mesos代码中大篇幅引用libprocess,其中定义了大量异步编程的原语,包括future、promise这些在c++11中也有的概念,onReady、onAny等回调注册接口,以及then串接异步调用等等强大功能。

future/promise 概念

先看cplusplus.com官方定义:

1
2
3
4
1. A future is an object that can retrieve a value from some provider object or function, 
properly synchronizing this access if in different threads.
2. A promise is an object that can store a value of type T to be retreieved by a future
object (possibly in another thread), offering a synchronization point.

libprocess中实现了一套类似的future/promise(类比std::future/std::promise),其思想与c++很类似,future读,promise写,消费者持有future,生产者持有promise。

callback

Future对象在函数返回值和入参间传递,存在多个消费者持有Future对象的多份拷贝的情况,因此Future使用一个共享指针成员维护唯一一份Data,在Data中记录Future状态和一系列callback,这些callback由onXXX接口注册,当生产者调用Promise的set等接口改变Future状态时将调用对应的callback。then也应用了callback机制。

then

先看示例代码:

1
2
3
4
5
Future<string> S = readyFuture()
.then(lambda::bind(&second, lambda::_1))
.then(lambda::bind(&third, lambda::_1));

string s = S.get();

等同于:

1
2
3
4
5
Future<bool> A = oneFuture();
Future<int> B = second(A.get());
Future<string> S = third(B.get());

string s = S.get();