Thread-safety and lazy-initialization of libraries

Sergey Protko via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 30 14:56:02 PDT 2014


On Monday, 30 June 2014 at 21:36:10 UTC, Rene Zwanenburg wrote:
> On Monday, 30 June 2014 at 21:32:34 UTC, Sergey Protko wrote:
>> On Monday, 30 June 2014 at 21:05:32 UTC, bearophile wrote:
>>> Sergey Protko:
>>>
>>>> libmpg123 has mpg123_init and mpg123_exit functions, which 
>>>> are not thread-safe, so we should to call them only once per 
>>>> process. Most of useful libraries also has such stuff. But 
>>>> manual initialization is killing all beauty of high-level 
>>>> bindings.
>>>
>>> I think module "static this" is thread-local, so in theory 
>>> you can use that. But I don't know if it's a good idea to 
>>> perform heavy computations inside those module static this.
>>>
>>> Bye,
>>> bearophile
>>
>> I thought about this. But static constructors doesn't solve 
>> problem with on-demand initialization in case, where there is 
>> several classes. For example Decoder and Encoder both requires 
>> library to be initialized before they are actually be used.
>
> Use a shared module constructor? It's called only once, not 
> per-thread.
>
>
> module mpg123;
>
> shared static this()
> {
>   mpg123_init();
> }
>
> shared static ~this()
> {
>   mpg123_exit();
> }

Oh, sorry. I doesn't thought about module constructors. But how 
we should handle errors on initialization? I can't just throw an 
exception from module constructor. Also this way isn't lazy at 
all)

I could write something like thread-safe singleton with lazy 
initialization, which returns status of library (OK or error 
code), but i not sure about that. Is it reasonable way?


More information about the Digitalmars-d-learn mailing list