pcp
[Top] [All Lists]

Re: [pcp] Another thread-safe issue

To: kenj@xxxxxxxxxxxxxxxx
Subject: Re: [pcp] Another thread-safe issue
From: Max Matveev <makc@xxxxxxxxx>
Date: Wed, 23 Mar 2011 11:16:33 +1100
Cc: pcp@xxxxxxxxxxx
In-reply-to: <1300826238.12077.130.camel@xxxxxxxxxxxxxxxx>
References: <1300826238.12077.130.camel@xxxxxxxxxxxxxxxx>
On Wed, 23 Mar 2011 07:37:18 +1100, Ken McDonell wrote:

 kenj> In several of places within libpcp we return a pointer to a static
 kenj> buffer ... since the buffer contents are not constant, this is not
 kenj> thread-safe.

 kenj> The routines are: pmAtomStr, pmTypeStr, pmUnitsStr, pmIDStr, pmInDomStr,
 kenj> __pmLogName, pmNumberStr, __pmPDUTypeStr and __pmTimezone.

 kenj> There are 3 possible fixes:

 kenj> 1. UCB-style, add func_r variants with an additional parameter that is
 kenj> the buffer of an assumed sufficient size.

 kenj> 2. Change the API semantics to return malloc'd buffers that the caller
 kenj> must free.

 kenj> 3. POSIX-style, add new functions for each, with an additional pair of
 kenj> arguments at the beginning to identify a caller allocated buffer and the
 kenj> length of that buffer (e.g. strftime) ... and discourage the use of the
 kenj> old functions.

 kenj> Thoughts?

You can use thread-local data - modern versions of gcc have good
support for it. E.g.

static __thread char    buf[SOME_SIZE];

char *pmIDStr(pmID pmid)
{
        snprintf(buf, sizeof(buf), "%u.%u.%u", p->domain, p->cluster, p->item);
        return buf;
}

This way each thread will have its own copy of buf and as long as
strings don't leak across threads it works well.

The disadvantage is:
    - passing pointers to different threads generates obscure bugs
    - non-gcc compilers will have harder time implementing this.

max

<Prev in Thread] Current Thread [Next in Thread>