1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
3 <title>Using APR Pools</title>
7 Last modified at [$Date: 2004-11-24 17:51:51 -0500 (Wed, 24 Nov 2004) $]
10 <h1>Using APR Pools</h1>
13 From <a href="http://subversion.tigris.org/">Subversion</a>, we
14 have learned a <em>lot</em> about how to use pools in a heavily
15 structured/object-based environment.
16 <a href="http://httpd.apache.org/">Apache httpd</a> is a
17 completely different beast: "allocate a request pool. use
22 In a complex app, that request-style of behavior is not
23 present. Luckily, the "proper" use of pools can be described in
29 Objects should not have their own pools. An object is
30 allocated into a pool defined by the constructor's caller. The
31 <strong>caller</strong> knows the lifetime of the object and
32 will manage it via the pool. Generally, this also means that
33 objects will not have a "close" or a "free" since those
34 operations will happen implicitly as part of the destruction
35 of the pool the objects live within.
40 Functions should not create/destroy pools for their
41 operation; they should use a pool provided by the
42 caller. Again, the <strong>caller</strong> knows more about
43 how the function will be used, how often, how many times,
44 etc. Thus, it should be in charge of the function's memory
48 As an example, the caller might know that the app will exit
49 upon the function's return. Thus, the function would be
50 creating extra work if it built and destroyed a
51 pool. Instead, it should use the passed-in pool, which the
52 caller is going to be tossing as part of app-exit anyways.
58 Whenever an unbounded iteration occurs, a subpool should be
59 used. The general pattern is:
63 subpool = apr_create_subpool(pool);
64 for (i = 0; i < n; ++i) {
65 apr_pool_clear(subpool);
67 do_operation(..., subpool);
69 apr_pool_destroy(subpool);</pre>
72 This pattern prevents the 'pool' from growing unbounded and
73 consuming all of memory. Note that it is slightly more
74 optimal to clear the pool on loop-entry. This pattern also
75 allows for a '<tt>continue</tt>' to occur within the loop,
76 yet still ensure the pool will be cleared.
81 Given all of the above, it is pretty well mandatory to pass a
82 pool to <em>every</em> function. Since objects are not
83 recording pools for themselves, and the caller is always
84 supposed to be managing memory, then each function needs a
85 pool, rather than relying on some hidden magic pool. In
86 limited cases, objects may record the pool used for their
87 construction so that they can construct sub-parts, but these
88 cases should be examined carefully. Internal pools can lead to
89 unbounded pool usage if the object is not careful.
94 <address>Greg Stein</address>
95 <!-- Created: Wed Jun 25 14:39:57 PDT 2003 -->
97 Last modified: Wed Jun 25 14:50:19 PDT 2003