[Xcb] Thread safety of XCB.

Josh Triplett josh at joshtriplett.org
Wed Oct 3 00:18:51 PDT 2012

On Wed, Oct 03, 2012 at 08:55:25AM +0300, John Found wrote:
> Thanks for the reply.
> On Tue, 2 Oct 2012 20:58:45 -0700
> Josh Triplett <josh at joshtriplett.org> wrote:
> > First of all, since you use threads with Xlib, you must call
> > XInitThreads before any other call to Xlib, including XOpenDisplay.
> > Have you done so?
> Yes, my application calls XInitThreads before any other XLib call.
> > Second, even though you don't use pthreads, Xlib and XCB do so
> > internally; specifically, they use pthread locks and condition variables
> > for synchronization.  If your application does not link to libpthread,
> > those internal uses will go to the stub functions in glibc (or the stub
> > functions in libpthread-stubs on systems without stubs in their libc), which don't
> > actually do proper locking.  So, if you use threading with Xlib or XCB,
> > you must compile with -pthread, even if you don't use libpthread
> > yourself.  (Or, alternatively, you can call Xlib and XCB exclusively
> > from a single thread.)
> I am using XLib as a shared library, so I am sure it does calls the proper 
> pthread functions, not the stubs in the glibc.

Not true.  Neither Xlib nor XCB links to libpthread directly; they link
to the weak symbols provided in glibc, overridden by libpthread if
available, but they won't actually pull in libpthread themselves.  (That
way, they have no synchronization overhead in single-threaded programs.)
If your application does not pull in libpthread itself, then Xlib and
XCB will not use the real pthread functions, and they will fail with an
error caused by manipulating internal data structures from multiple
threads with no synchronization, such as the error you observed.

Try linking your program with -pthread and attempting to reproduce the

As one other possibility, what versions of Xlib and XCB do you use?
Let's rule out the possibility that you have an old version with a bug
in it; at least one old bug triggered the assertion you observed.

> So, all synchronizations should be OK, except if XCB somehow accepts all of
> my thread calls (created by sys_clone) as a single thread calls.

XCB does not need to know what thread you call from; it simply does
appropriate synchronization on all calls.  As long as the pthread
functions work, it will do proper synchronization, whether you create
your threads via clone or libpthread.  (Assuming that the pthread
implementation itself works with threads not created via pthread_create,
which I would hope it does.)

- Josh Triplett

More information about the Xcb mailing list