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

The schedpolicy and schedparam attributes, set respectively by pthread_attr_setschedpolicy and pthread_attr_setschedparam, specify the explicit scheduling policy and parameters for the attributes object. Pthreads does not specify a default value for either of these attributes, which means that each implementation may choose some "appropriate" value. A realtime operating system intended for embedded controller applications, for example, might choose to create threads by default with SCHED_FIFO policy, and, perhaps, some medium-range priority.

Most multiuser operating systems are more likely to use a nonstandard "time-share" scheduling policy by default, causing threads to be scheduled more or less as processes have always been scheduled. The system may, for example, temporarily reduce the priority of "CPU hogs" so that they cannot prevent other threads from making progress.

One example of a multiuser operating system is Digital UNIX, which supports two nonstandard timeshare scheduling policies. The foreground policy (SCHED_ FG_NP), which is the default, is used for normal interactive activity, and corresponds to the way nonthreaded processes are scheduled. The background policy (SCHED_BG_NP) can be used for less important support activities.

When you set the scheduling policy or priority attributes in an attributes object,you must also set the inheritsched attribute!

The inheritsched attribute, which you can set by calling pthread_attr_setinheritsched, controls whether a thread you create inherits scheduling information from the creating thread, or uses the explicit scheduling information in the schedpolicy and schedparam attributes. Pthreads does not specify a default value for inheritsched, either, so if you care about the policy and scheduling parameters of your thread, you must always set this attribute.

Set the inheritsched attribute to PTHREAD_INHERIT_SCHED to cause a new thread to inherit the scheduling policy and parameters of the creating thread. Scheduling inheritance is useful when you're creating "helper" threads that are working on behalf of the creator — it generally makes sense for them to run at the same policy and priority. Whenever you need to control the scheduling policy or parameters of a thread you create, you must set the inheritsched attribute to PTHREAD_EXPLICIT_SCHED.

58-118 The following program, sched_attr.c, shows how to use an attributes object to create a thread with an explicit scheduling policy and priority. Notice that it uses conditional code to determine whether the priority scheduling feature of Pthreads is supported at compilation time. It will print a message if the option is not supported and continue, although the program in that case will not do much. (It creates a thread with default scheduling behavior, which can only say that it ran.)

Although Solaris 2.5 defines _POSIX_THREAD_PRIORITY_SCHEDULING, it does not support the POSIX realtime scheduling policies, and attempting to set the policy attribute to SCHED_RR would fail. This program treats Solaris as it did not define the _POSIX_THREAD_PRIORITY_SCHEDULING option.

sched_attr.c

#include

2 #include

3 #include

4 #include "errors.h" 5

6 /*

7 * Thread start routine. If priority scheduling is supported,

8 * report the thread's scheduling attributes.

9 */

10 void *thread_routine (void *arg)

11 {

12  int my_policy;

13  struct sched_param my_param;

14  int status;

15

16 /*

17 * If the priority scheduling option is not defined, then we

18 * can do nothing with the output of pthread_getschedparam,

19 * so just report that the thread ran, and exit.

20 */

21 #if defined (_POSIX_THREAD_PRIORITY_SCHEDULING) && !defined (sun)

22  status = pthread_getschedparam (

23  pthread_self (), &my_policy, &my_param);

24  if (status != 0)

25  err_abort (status, "Get sched");

26  printf ("thread_routine running at %s/%d\n",

27  (my_policy == SCHED_FIFO ? "FIFO"

28  : (my_policy == SCHED_RR ? "RR"

29  : (my_policy == SCHED_OTHER ? "OTHER"

30  : "unknown"))),

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных