Path: csiph.com!aioe.org!.POSTED!not-for-mail From: Kaz Kylheku <217-679-0842@kylheku.com> Newsgroups: comp.programming.threads Subject: Re: pthread_once_t in dynamically allocated (and freed) memory? Date: Mon, 26 Feb 2018 02:29:43 +0000 (UTC) Organization: Aioe.org NNTP Server Lines: 28 Message-ID: <20180225181853.893@kylheku.com> References: <4a411f41-1032-4f7b-8148-5d2249029820@googlegroups.com> NNTP-Posting-Host: hlQwqVQo951TVKyinY4JRg.user.gioia.aioe.org X-Complaints-To: abuse@aioe.org User-Agent: slrn/pre1.0.0-18 (Linux) X-Notice: Filtered by postfilter v. 0.8.3 Xref: csiph.com comp.programming.threads:4060 On 2018-02-25, dave@boostpro.com wrote: > Hi, > > I want to dynamically allocate memory, then once, on demand, thread-safely initialize part of that memory, and potentially free the memory. Then later I want to repeat the process with what is potentially the same memory block (and thus the same address of pthread_once_t) that has been returned from the allocator. Does this > > a. "just work" as long as it is set up with PTHREAD_ONCE_INIT, or > b. do I need to do insert some kind of fence to ensure that all threads see the re-initialized memory, or > c. never work; don't do that! > d. something else I haven't thought of? It must work. Firstly, POSIX says that PTHREAD_ONCE_INIT is a constant. Thus it may be used in assignment. This is important because, by contrast, the PTHREAD_MUTEX_INITIALIZER is described as a macro that can be used for initialization, and not a constant. Secondly, there is a storage restriction on the phread_once_t control variable: namely, it may not be defined in automatic storage (i.e. non-static local variable). There is no restriction against pthread_once_t being in dynamic storage. > I ask because all the examples I can find store the pthread_once_t in > static storage and never re-initialize it. However, if that is in a shared library, it's dynamic anyway. The dynamic case is effectively exercised any time a shared library is dlopen'ed that has a file scope pthread_once_t.