Subject: Re: Thread safety issues

Re: Thread safety issues

From: Simon Josefsson <>
Date: Wed, 01 Sep 2010 17:17:02 +0200

jmk <> writes:

> On Tue, 2010-08-31 at 22:54 +0200, Simon Josefsson wrote:
>> It may be simpler to call libssh2_init globally before firing up any
>> threads. Then you only need to supply mutexes to the crypto library.
> Not feasible given the current design of my application -- all SSH code
> is contained within a module, which can be loaded by one or more
> threads.

Ouch. How does your application handle this for other libraries? There
are many libraries out there that need global initialization. So it may
make sense to consider making your application call a module-init
function before proceeding. Of course, this is speaking just generally,
and there may be reasons why this isn't an option for you.

> The core application doesn't have any SSH specific code in it.
> Fortunately, calling libssh2_init() multiple times doesn't *appear* to
> be causing me any issues.

The code looks like this:

libssh2_init(int flags)
    if (_libssh2_initialized == 0 && !(flags & LIBSSH2_INIT_NO_CRYPTO)) {

    _libssh2_init_flags |= flags;

    return 0;

So there IS a race condition if two threads call the function at the
same time and there is a thread switch between the '==' comparison and
the '++' operation. But typically this won't happen.

Just make sure you call libssh2_exit as many times you call
libssh2_init, if you care at all about resource de-allocation.

Received on 2010-09-01