You are currently viewing Do POSIX Threads Make Sense with Modern C++?
Photo by Suzy Hazelwood from Pexels

Do POSIX Threads Make Sense with Modern C++?

Using pthreads, the POSIX thread library, has been the accepted way to develop multi-threaded software on UNIX-based platforms for many years.  So, many years ago I created a higher-level thread library for C++ that provided an object oriented facade for the pthreads library.

The API was loosely based on Java’s original thread library. The base thread class has a pure abstract virtual method named run() which the user must override in a derived class, then a start() method is called to invoke the thread. It had lots of supporting features too such as a detached (daemon) state, starting the thread after a certain delay and restarting on a recurring basis. The pthread library was used exclusively.

One reason for developing this library was to provide platform-independent thread support by developing a Windows native version. I decided not to use boost::thread when it became available, but when threads were added to the C++ language (C++11) as std::thread, I thought my library had finally became obsolete.

I recently had to update some legacy software for Linux and used modern C++. I realized the software was using my outdated threads library, but decided to keep it because recompiling it with minor updates, still using pthreads, seemed easier than changing the application to use the std::thread API.

The software is working but if changes are needed in the future I will probably consider changing the application to use std::thread rather than updating the library to use it, leaving the application software unchanged.  While it is good to have a higher level abstraction to std::thread, the std::async is intended to do so.  Unfortunately, I’ve seen issues in the past with std::async on MacOS.  My particular application is not “heavily” multithreaded and not needed on Mac.

Posix threads might still be preferred today because:

  • pthread support is mature across most platforms, although third-party libraries are needed for some non-Posix systems
  • low-level access to pthreads or to the system supporting them will require direct pthread access
  • std::thread doesn’t provide access to all functionality of the underlying pthread system such as priorities or proper signal handling (I say pthread system here because there is kernel support as well as the pthread libraries)

For modern C++ development going forward, std::thread support might be preferred because:

  • It’s part of the language and provides a class library and type safety that pthread does not
  • It is portable to all platforms supporting modern C++
  • Exceptions from threads are handled as one would expect in std::async

So Yes, Posix threads make a lot of sense with modern C++, depending on our requirements for multithreaded software.