gnulib - GNU portability library - News
Gnulib supports portable multithreading
Item posted by Bruno Haible <haible> on Wed 30 Dec 2020 03:10:08 PM UTC.
There are three main motivations for using multiple threads in a program:
- To get computational tasks done is less time, by using more than one CPU core at once.
- For event handling. The older approach with signals and/or file descriptors in non-blocking mode leads to brittle and racey programs. Using separate threads that use read() or write() produces more reliable programs with simpler and thus more maintainable code.
- To otherwise simplify the logic of background tasks.
For the first case, the OpenMP standard and its implementation in GCC, libgomp, provide all you need. It uses multiple threads under the hood. Use the Autoconf macro AC_OPENMP for portability.
For the other cases, or when you want to control the threads yourself, you'll need to choose a multithreading API. Two such APIs are available across all platforms, through Gnulib:
- POSIX multithreading.
- ISO C multithreading, specified starting with ISO C 11.
POSIX multithreading and ISO C multithreading are similar. ISO C multithreading contains only the essential APIs, whereas POSIX multithreading has more features. For example, while both have locks/mutexes, only POSIX has spin-locks. And when creating a thread, only POSIX allows to specify thread attributes, such as its stack size or its scheduling priority. Also, lock initialization is straightforward in POSIX, but clumsy in ISO C.
Without Gnulib, none of these two APIs can be used across platforms:
- The POSIX API is generally available on all Unix platforms for the last ten years, with some bugs on older platforms such as HP-UX. On native Windows, there is a buggy implementation called 'winpthreads' for mingw (and mingw only — not usable with MSVC).
- The ISO C API is available only starting with glibc 2.28, FreeBSD 10, and NetBSD 9. Buggy implementations are also available in AIX 7 and Solaris 11.4.
With Gnulib, you can use either of these APIs across platforms:
- For the POSIX API, Gnulib adds an implementation for native Windows and fixes for the known bugs on Unix systems.
- For the ISO C API, Gnulib adds an implementation or fixes, as needed to make things work right.
My personal recommendation is:
- Use the POSIX API, except possibly for teaching computer science. If, at some point, you need thread attributes or spin-locks, you would be stuck with the ISO C API.
- On native Windows, use the POSIX API together with the configure option '--enable-threads=windows'. This option avoids the buggy 'winpthreads' library and instead uses the Gnulib implementation of the POSIX threads.
Powered by Savane 3.14-50d9.
Corresponding source code