talloc and threaded programs
Jeremy Allison
jra at samba.org
Fri Jun 20 10:45:19 MDT 2014
On Fri, Jun 20, 2014 at 03:20:38PM +0100, Phil Mayers wrote:
> I'm trying to troubleshoot some memory corruption issues in a
> threaded program using talloc, and I wanted to check a few things.
>
> First - the talloc page says a context must either be used by one
> thread or synchronised. Am I correct in assuming that this applies
> at one "level" of the context tree only i.e. this is illegal:
>
> /* main thread */
> c = talloc(toplevel, struct C);
> /* thread #2 */
> d = talloc(toplevel, struct C);
>
> ...but this is legal:
>
> /* main thread */
> c = talloc(toplevel, struct C);
> /* thread #2 */
> d = talloc(c, struct C);
> /* main thread */
> e = talloc(toplevel, struct C);
>
> ...because thread2 is not touching "toplevel"?
No, this is not safe. c is a child of
toplevel, which is being messed with
in the other thread.
> Similarly, this is legal:
>
> /* main thread */
> c = talloc(toplevel, struct C);
> /* thread #2 */
> d = talloc(c, struct C);
> e = talloc(d, struct C);
> talloc_free(e);
>
> ...but this is illegal:
>
> /* main thread */
> c = talloc(toplevel, struct C);
> /* thread #2 */
> d = talloc(c, struct C);
> talloc_free(d); /* will mutate "c"
> /* main thread */
> e = talloc(c, struct C);
>
> Basically - I'm ok to use (but not delete) children of a context in
> a different thread?
No. Keep your contexts completely separate.
For example:
>From the main thread:
/* Ensure there is no shared state
from talloc's off the NULL context.
You only need this if you have
previously called talloc_enable_null_tracking()
or talloc_enable_null_tracking_no_autofree().
If not, the null context will be NULL
and you can skip this.
*/
talloc_disable_null_tracking();
#main thread
ctx1 = talloc(NULL, struct foo);
#Thread 2
ctx2 = talloc(NULL, struct bar);
Then from within the main thread
you can do anything you like to
ctx1, and from thread #2 you can
do anything you like to ctx2.
Don't mix *any* talloc's on the
ctx1 tree with the ctx2 tree.
Jeremy.
More information about the samba-technical
mailing list