Little Bobby Tables
Little Bobby Tables

Reputation: 5351

Non-preemptive Pthreads?

Is there a way to use pthreads without a scheduler, so context switch occurs only if a thread explicitly yields, or is blocked on a mutex/cond? If not, is there a way to minimize the scheduling overhead, so that forced context switches will occur as rarely as possible?

The question refers to the Linux gcc/g++ implementation of POSIX threads.

Upvotes: 3

Views: 2784

Answers (2)

EmeryBerger
EmeryBerger

Reputation: 3975

You can use Pth (a.k.a. GNU Portable Threads), a non-preemptive thread library. Configuring it with --enable-pthread will create a plug-in replacement for pthreads. I just built and tested this on my Mac and it works fine for a simple pthreads program.

From the 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.

Upvotes: 5

thiton
thiton

Reputation: 36059

If you have a process running in normal user land, context switches will naturally happen as part of the system operation - there is always another process that needs the CPU time. Preemptive context switches between your threads are quite well optimized by the OS already and are bound to be necessary sometimes.

If you really happen to have problems with excessive context switching, you are best off tweaking the Linux scheduler first, which is off-topic here. pthread_setschedprio and pthread_setschedparam can set some hints, but are limited to setting priorities, and the interpretation of these priorities is implementation-defined, i.e. up to the Linux scheduler.

Upvotes: 0

Related Questions