有没有一种方法可以在不使用调度程序的情况下使用pthread,因此仅当线程显式产生或在互斥锁/ cond上被阻塞时才进行上下文切换?如果不是,是否有一种方法可以最大程度地减少调度开销,从而使强制上下文切换尽可能少地发生?
该问题涉及POSIX线程的Linux gcc / g实现.
解决方法:
您可以使用非抢占式线程库Pth(也称为GNU Portable Threads).使用–enable-pthread对其进行配置将创建pthread的插件替代.我刚刚在Mac上构建并测试了它,它对于简单的pthreads程序也可以正常工作.
从自述文件:
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.