Re: [Libguestfs] [PATCH v3 3/5] threads: Use thread-local storage for errors.

Pino Toscano
Mon, 10 Jul 2017 11:48:13 -0000

On Tuesday, 27 June 2017 13:55:57 CEST Richard W.M. Jones
wrote:
> We permit the following constructs in libguestfs code:
>
>   if (guestfs_some_call (g) == -1) {
>     fprintf (stderr, "failed: error is %s\n", guestfs_last_error
(g));
>   }
>
> and:
>
>   guestfs_push_error_handler (g, NULL, NULL);
>   guestfs_some_call (g);
>   guestfs_pop_error_handler (g);
>
> Neither of these would be safe if we allowed the handle to be used
> from threads concurrently, since the error string or error handler
> could be changed by another thread.
>
> Solve this in approximately the same way that libvirt does: by making
> the error, current error handler, and stack of error handlers use
> thread-local storage (TLS).
>
> The implementation is not entirely straightforward, mainly because
> POSIX doesn't give us useful destructor behaviour, so effectively we
> end up creating our own destructor using a linked list.

I'm not sure which behaviour you are referring to, but it should work
just fine -- in the destructor function, cast the void* argument to the
error_data struct, and free the linked list associated.

The only problem is that the tls gnulib implementation on Windows
(actually, on mingw) makes no use for the destructor function, but
a) we don't have a working Windows port ATM (not even on other
   non-Linux Unices)
b) using pthread or pth on mingw would solve this

I'd just use the destructor function approach, so there is less
complexity involved, and the per-thread resources are properly free'd
on thread exit (and not piling up until the handle destruction).

--
Pino Toscano