Linux – Non-preemptive threading?

Non-preemptive threading?… here is a solution to the problem.

Non-preemptive threading?

Is there a way to use pthreads without a scheduler, so that context switching only happens when the thread explicitly gives way or is blocked on the mutex/cond? If not, is there a way to minimize scheduling overhead so that forced context switching occurs as little as possible?

The issue concerns the Linux gcc/g++ implementation of POSIX threads.

Solution

You can use the non-preemptive threading library Pth (aka GNU Portable Threads). Configuring it with –-enable-pthread creates a plugin instead of pthreads. I just built and tested it on my Mac and it works with a simple pthreads program.

Readme:

Pth is a very portable POSIX/ANSI-C based library for Unix platforms
which provides non-preemptive priority-based scheduling for multiple
threads of execution (aka `multithreading’) inside event-driven
applications. All threads run in the same address space of the server
application, but each thread has its own individual program-counter,
run-time stack, signal mask and errno variable.

The thread scheduling itself is done in a cooperative way, i.e., the
threads are managed by a priority- and event-based non-preemptive
scheduler. The intention is, that this way one can achieve better
portability and run-time performance than with preemptive scheduling.
The event facility allows threads to wait until various types of
events occur, including pending I/O on filedescriptors, asynchronous
signals, elapsed timers, pending I/O on message ports, thread and
process termination, and even customized callback functions.

Additionally Pth provides an optional emulation API for POSIX.1c
threads (`Pthreads’) which can be used for backward compatibility to
existing multithreaded applications.

Related Problems and Solutions