]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/doc/overview/strands.qbk
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / boost / libs / asio / doc / overview / strands.qbk
1 [/
2 / Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
3 /
4 / Distributed under the Boost Software License, Version 1.0. (See accompanying
5 / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 /]
7
8 [section:strands Strands: Use Threads Without Explicit Locking]
9
10 A strand is defined as a strictly sequential invocation of event handlers (i.e.
11 no concurrent invocation). Use of strands allows execution of code in a
12 multithreaded program without the need for explicit locking (e.g. using
13 mutexes).
14
15 Strands may be either implicit or explicit, as illustrated by the following
16 alternative approaches:
17
18 * Calling io_service::run() from only one thread means all event handlers
19 execute in an implicit strand, due to the io_service's guarantee that handlers
20 are only invoked from inside run().
21
22 * Where there is a single chain of asynchronous operations associated with a
23 connection (e.g. in a half duplex protocol implementation like HTTP) there is
24 no possibility of concurrent execution of the handlers. This is an implicit
25 strand.
26
27 * An explicit strand is an instance of `io_service::strand`. All event handler
28 function objects need to be wrapped using `io_service::strand::wrap()` or
29 otherwise posted/dispatched through the `io_service::strand` object.
30
31 In the case of composed asynchronous operations, such as `async_read()` or
32 `async_read_until()`, if a completion handler goes through a strand, then all
33 intermediate handlers should also go through the same strand. This is needed to
34 ensure thread safe access for any objects that are shared between the caller
35 and the composed operation (in the case of `async_read()` it's the socket,
36 which the caller can close() to cancel the operation). This is done by having
37 hook functions for all intermediate handlers which forward the calls to the
38 customisable hook associated with the final handler:
39
40 struct my_handler
41 {
42 void operator()() { ... }
43 };
44
45 template<class F>
46 void asio_handler_invoke(F f, my_handler*)
47 {
48 // Do custom invocation here.
49 // Default implementation calls f();
50 }
51
52 The `io_service::strand::wrap()` function creates a new completion handler that
53 defines `asio_handler_invoke` so that the function object is executed through
54 the strand.
55
56 [heading See Also]
57
58 [link boost_asio.reference.io_service__strand io_service::strand],
59 [link boost_asio.tutorial.tuttimer5 tutorial Timer.5],
60 [link boost_asio.examples.cpp03_examples.http_server_3 HTTP server 3 example].
61
62 [endsect]