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

Pthreads is intended to address a wide variety of audiences. High-performance computational programs can use it to support parallel decomposition of loops. Realtime programs can use it to support concurrent realtime I/O. Database and network servers can use it to easily support concurrent clients. Business or software development programs can use it to take advantage of parallel and concurrent operations on time-sharing systems.

The Pthreads standard allows you to determine which optional capabilities are provided by the system, by defining a set of feature-test macros, which are shown in Table 9.1. Any implementation of Pthreads must inform you whether each option is supported, by three means:

• By making a formal statement of support in the POSIX Conformance Document. You can use this information to help design your application to work on specific systems.

• By defining compile-time symbolic constants in the header file. You can test for these symbolic constants using #ifdef or #ifndef preprocessor conditionals to support a variety of Pthreads systems.

• By returning a positive nonzero value when the sysconf function is called with the associated sysconf symbol. (This is not usually useful for the "feature-test" macros that specify whether options are present — if they are not, the associated interfaces usually are not supplied, and your code will not link, and may not even compile.)

You might, for example, choose to avoid relying on priority scheduling because after reading the conformance documents you discovered that three out of the four systems you wish to support do not provide the feature. Or you might prefer to use priority inheritance for your mutexes on systems that provide the feature, but write the code so that it will not try to access the mutex protocol attribute on systems that do not provide that option.

Symbolic constant,Description
sysconf symbol name
_POSIX_THREADS _SC_THREADSYou can use threads (if your system doesn't define this, you're out of luck).
_POSIX_THREAD_ATTR_STACKSIZE _SC_THREAD_ATTR_STACKSIZEYou can control the size of a thread's stack.
_POSIX_THREAD_ATTR_STACKADDR _SC_THREAD_ATTR_STACKADDRYou can allocate and control a thread's stack.
_POSIX_THREAD_PRIORITY_SCHEDULING _SC_THREAD_PRIORITY_SCHEDULINGYou can use realtime scheduling.
_POSIX_THREAD_PRIO_INHERIT _SC_THREAD_PRIO_INHERITYou can create priority inheritance mutexes.
_POSIX_THREAD_PRIO_PROTECT _SC_THREAD_PRIO_PROTECTYou can create priority ceiling mutexes.
_POSIX_THREAD_PROCESS_SHARED _SC_THREAD_PROCESS_SHAREDYou can create mutexes and condition variables that can be shared with another process.
_POSIX_THREAD_SAFE_FUNCTIONS _SC_THREAD_SAFE_FUNCTIONSYou can use the special "_r" library functions that provide thread-safe behavior.

TABLE 9.1POSIX 1003.1c-1995 options

9.2 POSIX1003.1c-1995 limits

The Pthreads standard allows you to determine the run-time limits of the system that may affect your application, for example, how many threads you can create, by defining a set of macros, which are shown in Table 9.2. Any implementation of Pthreads must inform you of its limits, by three means:

• By making a formal statement in the POSIX Conformance Document. You can use this information to help design your application to work on specific systems.

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

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

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

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

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

Программирование, программы, базы данных
Delphi. Трюки и эффекты
Delphi. Трюки и эффекты

«Delphi. Трюки и эффекты», как и все издания данной серии, адресована тем, кто хочет научиться делать с помощью уже знакомых программных пакетов новые, интересные вещи. В первой части книги многое говорится о среде разработки Delphi (самых последних версий) и программировании на языке Object Pascal. Благодаря этому издание подходит и новичкам, и начинающим программистам. Вторая (основная) часть книги описывает удивительные возможности, скрытые в языке, и на примерах учит читателя программистским фокусам – от «мышек-невидимок» и «непослушных окон» до воспроизведения МРЗ и управления офисными программами Word и Excel из приложений Delphi. Купив эту книгу, вы пройдете непростой путь к вершинам программистского мастерства весело и интересно.

Валерий Викторович Борисок , Юрий Иванович Корвель , Александр Анатольевич Чиртик

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