.@ Tony Finch – blog

Earlier this week I needed to know how to write a thread-aware library so that it’s as easy as possible to link it with both threaded and non-threaded programs.

By “thread-aware” I mean that the library needs to lock its shared data structures when it is linked with a threaded program, as opposed to being thread-safe by partitioning its data so that it is naturally used by only one thread at a time. Thread-aware code needs to call functions like pthread_mutex_lock() but does not itself create threads. When it is linked to a non-threaded program the locking calls should be no-ops.

On IRC we discussed various more or less ugly compiler and linker tricks to redirect pthread calls to no-op stubs in non-threaded programs. 👤ewx said that the OS ought to come with a stub library, and 👤cjwatson and 👤pm215 said that Linux and HP-UX have the stubs built-in to libc. I found that BSD does the same, and that this fact is relied on by such prominent code as X11, so it’s sufficiently portable for my purposes.

So in the end it turns out that you don’t need to do anything special: just make whatever pthread calls you need. If the program is threaded (i.e. it links to libpthread) the calls will perform the necessary locking. If the program is not threaded there will be no libpthread to override the stub definitions in libc, so the locking calls will do nothing. Sweet.