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

You can think of an attributes object as a private structure. You read or write the "members" of the structure by calling special functions, rather than by accessing public member names. For example, you read the stacksize attribute from a thread attributes object by calling pthread_attr_getstacksize, or write it by calling pthread_attr_setstacksize.

In a simple implementation of Pthreads the type pthread_attr_t might be a typedef struct and the get and set functions might be macros to read or write members of the variable. Another implementation might allocate memory when you initialize an attributes object, and it may implement the get and set operations as real functions that perform validity checking.

Threads, mutexes, and condition variables each have their own special attributes object type. Respectively, the types are pthread_attr_t, pthread_ mutexattr_t, and pthread_condattr_t.

<p>5.2.1 Mutex attributes</p>

pthread_mutexattr_t attr;

int pthread_mutexattr_init (pthread_mutexattr_t *attr);

int pthread_mutexattr_destroy (

pthread_mutexattr_t *attr);

#ifdef _POSIX_THREAD_PROCESS_SHARED

int pthread_mutexattr_getpshared (

pthread_mutexattr_t *attr, int *pshared); int pthread_mutexattr_setpshared (

pthread_mutexattr_t *attr, int pshared);

#endif

Pthreads defines the following attributes for mutex creation: pshared, protocol, and prioceiling. No system is required to implement any of these attributes, however, so check the system documentation before using them.

You initialize a mutex attributes object by calling pthread_mutexattr_init, specifying a pointer to a variable of type pthread_mutexattr_t, as in mutex_ attr.c, shown next. You use that attributes object by passing its address to pthread_mutex_init instead of the NULL value we've been using so far.

If your system provides the _POSIX_THREAD_PROCESS_SHARED option, then it supports the pshared attribute, which you can set by calling the function pthread_mutexattr_setpshared. If you set the pshared attribute to the value PTHREAD_PROCESS_SHARED, you can use the mutex to synchronize threads within separate processes that have access to the memory where the mutex (pthread_ mutex_t) is initialized. The default value for this attribute is PTHREAD_PROCESS_PRIVATE.

The mutex_attr.c program shows how to set a mutex attributes object to create a mutex using the pshared attribute. This example uses the default value. PTHREAD_PROCESS_PRIVATE, to avoid the additional complexity of creating shared memory and forking a process. The other mutex attributes, protocol and prioceiling, will be discussed later in Section 5.5.5.

mutex_attr.c

1 #include

2 #include "errors.h"

3

4 pthread_mutex_t mutex;

5

6 int main (int argc, char *argv[])

7 {

8  pthread_mutexattr_t mutex_attr;

9  int status;

10

11  status = pthread_mutexattr_init (&mutex_attr);

12  if (status != 0)

13  err_abort (status, "Create attr");

14 #ifdef _POSIX_THREAD_PROCESS_SHARED

15  status = pthread_mutexattr_setpshared (

16  &mutex_attr, PTHREAD_PROCESS_PRIVATE);

17  if (status != 0)

18  err_abort (status, "Set pshared");

19 #endif

20  status = pthread_mutex_init (&mutex, &mutex_attr);

21  if (status != 0)

22  err_abort (status, "Init mutex");

23  return 0;

24 }

<p><strong>5.2.2 Condition variable attributes</strong></p>

pthread_condattr_t attr;

int pthread_condattr_init (pthread_condattr_t *attr);

int pthread_condattr_destroy (

pthread_condattr_t *attr);

#ifdef _POSIX_THREAD_PROCESS_SHARED

int pthread_condattr_getpshared (

pthread_condattr_t *attr, int *pshared);

int pthread_condattr_setpshared (

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

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

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

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

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

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

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

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

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