cURL / Mailing Lists / curl-library / Single Mail

curl-library

Re: Can't call curl_global_init from a thread -- understanding the architecture

From: Dan Fandrich <dan_at_coneharvesters.com>
Date: Mon, 6 Oct 2014 11:22:48 +0200

On Mon, Oct 06, 2014 at 08:09:51AM +0200, Tor Arntsen wrote:
> On 4 October 2014 23:05, Dan Fandrich <dan_at_coneharvesters.com> wrote:
> > On Sat, Oct 04, 2014 at 04:55:40PM -0400, K. Frank wrote:
>
> >> First, do I understand correctly that if, say, I were to have
> >> main() in a perfectly ordinary C program spawn a thread
> >> (say, pthread_create), then it would be illegal for that thread
> >> to call curl_global_init (even if no other thread in the program
> >> were to call any curl functions)?
> >
> > Yes. But sometimes you will be lucky and it will work.
>
> I believe this is a too generic statement. It is not threads per se
> that is the problem - after all, on Linux and some other systems
> there's nothing inherently different between the thread that runs
> main() or any other thread - they are all just threads. Some processes
> happen to have more than one thread, that's all.

Sure, this is an overly broad prohibition, but it's the only one that is
guaranteed to be safe. If you're sure about the environment you'll be running
in, which a library cannot, then you can take shortcuts.

> The issue is about race condtions only. If main() spawns a single
> thread which then goes on to do curl_global_init() and then manages
> all its own threads from there, then that's the same as if main()
> itself did it.
> What you cannot do (and that follows from the above) is to spawn
> multiple threads with copies of that code which may call
> curl_global_init().. if you do, then you will have to take care and
> play around with flags and mutexes etc. And that would indicate a
> non-optimal design.

It's not just the libcurl code that's involved, though. If you read some of the
other threads on this issue, there can be some subtle and unexpected effects
when other code uses the same dependencies as libcurl itself.

>>> Dan
-------------------------------------------------------------------
List admin: http://cool.haxx.se/list/listinfo/curl-library
Etiquette: http://curl.haxx.se/mail/etiquette.html
Received on 2014-10-06