Книга: Programming with POSIX® Threads

5.2.1 Mutex attributes

5.2.1 Mutex attributes

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 <pthread.h>
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 }

Оглавление книги


Генерация: 8.433. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз