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

pthread_condattr_t *attr, int pshared);

#endif

Pthreads defines only one attribute for condition variable creation, pshared. No system is required to implement this attribute, so check the system documentation before using it. You initialize a condition variable attributes object using pthread_condattr_init, specifying a pointer to a variable of type pthread_ condattr_t, as in cond_attr.c, shown next. You use that attributes object by passing its address to pthread_cond_init instead of the NULL value we've been using so far.

If your system defines _POSIX_THREAD_PROCESS_SHARED then it supports the pshared attribute. You set the pshared attribute by calling the function pthread_ condattr_setpshared. If you set the pshared attribute to the value PTHREAD_ PROCESS_SHARED, the condition variable can be used by threads in separate processes that have access to the memory where the condition variable (pthread_ cond_t) is initialized. The default value for this attribute is PTHREAD_PROCESS_PRIVATE.

The cond_attr.c program shows how to set a condition variable attributes object to create a condition variable 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.

cond_attr.c

1 #include

2 #include "errors.h"

3

4 pthread_cond_t cond;

5

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

7 {

8  pthread_condattr_t cond_attr;

9  int status;

10

11  status = pthread_condattr_init (&cond_attr);

12  if (status != 0)

13  err_abort (status, "Create attr");

14 #ifdef _POSIX_THREAD_PROCESS_SHARED

15  status = pthread_condattr_setpshared (

16  &cond_attr, PTHREAD_PROCESS_PRIVATE);

17  if (status != 0)

18  err_abort (status, "Set pshared");

19 #endif

20  status = pthread_cond_init (&cond, &cond_attr);

21  if (status != 0)

22  err_abort (status, "Init cond");

23 return 0;

24 }

To make use of a PTHREAD_PROCESS_SHARED condition variable, you must also use a PTHREAD_PROCESS_SHARED mutex. That's because two threads that synchronize using a condition variable must also use the same mutex. Waiting for a condition variable automatically unlocks, and then locks, the associated mutex. So if the mutex isn't also created with PTHREAD_PROCESS_SHARED, the synchronization won't work.

<p>5.2.3 Thread attributes</p>

pthread_attr_t attr;

int pthread_attr_init (pthread_attr_t *attr);

int pthread_attr_destroy (pthread_attr_t *attr); int pthread_attr_getdetachstate (pthread_attr_t *attr, int *detachstate);

int pthread_attr_setdetachstate (pthread_attr_t *attr, int detachstate);

#ifdef _POSIX_THREAD_ATTR_STACKSIZE

int pthread_attr_getstacksize (pthread_attr_t *attr, size_t *stacksize);

int pthread_attr_setstacksize (pthread_attr_t *attr, size_t stacksize);

#endif

#ifdef _POSIX_THREAD_ATTR_STACKADDR

int pthread_attr_getstackaddr (pthread_attr_t *attr, void *stackaddr);

int pthread_attr_setstackaddr (pthread_attr_t *attr, void **stackaddr);

#endif

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

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

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

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

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

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