Folks,

We've recently seen several bugs and potential issues related to lambda
captures in our codebase. To help us avoid these problems in the future, we
would like to touch on few general guidelines now. After 1.0 release, we
will take some time and revisit our lambda guidelines and think about what
primitives we can add in order to enforce the rules.

1) Use `defer` to execute on the same context.
If your lambda captures `this` to capture the actor context, most probably
you want it to be executed in the actor’s context. you should use `defer()`
to achieve this. For an example, see [1].

2) `this` should typically point to the actor instance.
When you capture `this`, make sure it represents the actor instance onto
which you `defer()` or `dispatch()`. If you are doing otherwise, make sure
you capture the reason in a comment. For an example, see [2], the second
and the third hunks.

3) Avoid capturing by reference.
While capturing by reference is allowed, captured objects must not be
destructed before they are used in the lambda. For an example, see [3].
Except common cases, like using a library that always executes lambdas
immediately [4], you should always write a comment explaining that capture
by reference is done on purpose, e.g. [5]. IMPORTANT: capturing `this` by
value and using a member variable is effectively capture by reference!

AlexR & MPark.

[1]
https://github.com/apache/mesos/commit/97124ac72bbc42f809b800fe2da383dc43b1b34e
[2]
https://github.com/apache/mesos/commit/89d072d8567ccdcf11d1b1093350f393885fc593
[3]
https://github.com/apache/mesos/commit/54b82e5713243f44e7e2a617f53bce872381b36a
[4]
https://github.com/apache/mesos/blob/149f4c55b951e5eaea1cb5faf400089dd36c355a/src/master/http.cpp#L1251
[5]
https://github.com/apache/mesos/blob/149f4c55b951e5eaea1cb5faf400089dd36c355a/src/master/http.cpp#L1239-L1241

Reply via email to