Читаем Programming with POSIX® Threads полностью

const pthread_attr_t *attr, int *inheritsched);

int pthread_attr_setinheritsched (

pthread_attr_t *attr, int inheritsched);

int pthread_attr_getschedparam (

constpthread_attr_t *attr,

struct sched_param *param);

int pthread_attr_setschedparam (

pthread_attr_t *attr,

const struct sched_param *param);

int pthread_attr_getschedpolicy (

const pthread_attr_t *attr, int *policy);

int pthread_attr_setschedpolicy (

pthread_attr_t *attr, int policy);

int pthread_getschedparam (pthread_t thread,

int *policy, struct sched_param *param);

int pthread_setschedparam (

pthread_t thread, int policy,

const struct sched_param *param);

A Pthreads system that supports _POSIX_THREAD_PRIORITY_SCHEDULING must provide a definition of the struct sched_param structure that includes at least the member sched_priority. The sched_priority member is the only scheduling parameter used by the standard Pthreads scheduling policies, SCHED_FIFO and SCHED_RR. The minimum and maximum priority values (sched_priority member) that are allowed for each scheduling policy can be determined by calling sched_get_priority_min or sched_get_priority_max, respectively, for the scheduling policy. Pthreads systems that support additional, nonstandard scheduling policies may include additional members.

The SCHED_FIFO (first in, first out) policy allows a thread to run until another thread with a higher priority becomes ready, or until it blocks voluntarily. When a thread with SCHED_FIFO scheduling policy becomes ready, it begins executing immediately unless a thread with equal or higher priority is already executing.

The SCHED_RR (round-robin) policy is much the same, except that if a thread with SCHED_RR policy executes for more than a fixed period of time (the timeslice interval) without blocking, and another thread with SCHED_RR or SCHED_FIFO policy and the same priority is ready, the running thread will be preempted so the ready thread can be executed.

When threads with SCHED_FIFO or SCHED_RR policy wait on a condition variable or wait to lock a mutex, they will be awakened in priority order. That is, if a low-priority SCHED_FIFO thread and a high-priority SCHED_FIFO thread are both waiting to lock the same mutex, the high-priority thread will always be unblocked first when the mutex is unlocked.

Pthreads defines the name of an additional scheduling policy, called SCHED_OTHER. Pthreads, however, says nothing at all regarding what this scheduling policy does. This is an illustration of an unofficial POSIX philosophy that has been termed "a standard way to be nonstandard" (or, alternately, "a portable way to be nonportable"). That is, when you use any implementation of Pthreads that supports the priority scheduling option, you can write a portable program that creates threads running in SCHED_OTHER policy, but the behavior of that program is nonportable. (The official explanation of SCHED_OTHER is that it provides a portable way for a program to declare that it does not need a realtime scheduling policy.)

The SCHED_OTHER policy may be an alias for SCHED_FIFO, or it may be SCHED_RR, or it may be something entirely different. The real problem with this ambiguity is not that you don't know what SCHED_OTHER does, but that you have no way of knowing what scheduling parameters it might require. Because the meaning of SCHED_OTHER is undefined, it does not necessarily use the sched_priority member of the struct sched_param structure, and it may require additional, nonstandard members that an implementation may add to the structure. If there's any point to this, it is simply that SCHED_OTHER is not portable. If you write any code that uses SCHED_OTHER you should be aware that the code is not portable — you are, by definition, depending on the SCHED_OTHER of the particular Pthreads implementation for which you wrote the code.

Перейти на страницу:

Похожие книги

C++: базовый курс
C++: базовый курс

В этой книге описаны все основные средства языка С++ - от элементарных понятий до супервозможностей. После рассмотрения основ программирования на C++ (переменных, операторов, инструкций управления, функций, классов и объектов) читатель освоит такие более сложные средства языка, как механизм обработки исключительных ситуаций (исключений), шаблоны, пространства имен, динамическая идентификация типов, стандартная библиотека шаблонов (STL), а также познакомится с расширенным набором ключевых слов, используемым в .NET-программировании. Автор справочника - общепризнанный авторитет в области программирования на языках C и C++, Java и C# - включил в текст своей книги и советы программистам, которые позволят повысить эффективность их работы. Книга рассчитана на широкий круг читателей, желающих изучить язык программирования С++.

Герберт Шилдт

Программирование, программы, базы данных
Секреты приложений Google
Секреты приложений Google

Даже продвинутые пользователи Интернета не подозревают о тех огромных возможностях, которые предоставляют сервисы Google. Автор рассказывает о таких «секретах» сервисов, которые просто немедленно хочется использовать! Создавать сайты и презентации, бродить по улочкам Парижа, изучать звездное небо – все это доступно каждому, кто сидит у экрана монитора и имеет доступ в Интернет. Книга научит вас работать с веб-приложениями и тысячекратно увеличить свои возможности с помощью новейших технологий. Она написана легким, доступным языком и не требует от читателя наличия каких-либо специальных знаний. Книга содержит множество примеров, иллюстраций и будет полезна всем, кто не стоит на месте и стремится сделать свою жизнь более насыщенной и интересной.

Денис Балуев , Денис Игоревич Балуев

Программирование, программы, базы данных / Интернет / Программное обеспечение / Книги по IT