Fixed race condition in API global state open/close

The atomic reference counter for the global API state (unit registry etc)
wasn't enough to prevent the situation where a new thread reopens the API
after the refcount has reached zero, but before the closing thread is
actually done closing the API. Now there's an additional atomic flag, and
logic to deal with this situation.

There was also the possibility of a thread concluding that the API is already
open and just going ahead, failing to notice that the thread that was there
first, hasn't actually opened the API yet! A non-zero refcount now means we
check that the API actually is initialized before moving on.

Added apistress.c, to actually test these extremely rare situations.

Closes #180.