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

17  return status;

18 status = pthread_cond_init (&rwl->read, NULL);

19 if (status != 0) {

20 /* if unable to create read CV, destroy mutex */

21  pthread_mutex_destroy (&rwl->mutex);

22  return status;

23 }

24 status = pthread_cond_init (&rwl->write, NULL);

25 if (status != 0) {

26 /* if unable to create write CV, destroy read CV and mutex */

27  pthread_cond_destroy (&rwl->read);

28  pthread_mutex_destroy (&rwl->mutex);

29  return status;

30 }

31 rwl->valid = RWLOCK_VALID;

32 return 0;

33 }

Part 2 shows the rwl_destroy function, which destroys a read/write lock.

8-9 We first try to verify that the read/write lock was properly initialized by checking the valid member. This is not a complete protection against incorrect usage, but it is cheap, and it will catch some of the most common errors. See the annotation for barrier.c, part 2, for more about how the valid member is used.

10-30 Check whether the read/write lock is in use. We look for threads that are using or waiting for either read or write access. Using two separate if statements makes the test slightly more readable, though there's no other benefit.

36-39 As in barrier_destroy, we destroy all Pthreads synchronization objects, and store each status return. If any of the destruction calls fails, returning a nonzero value, rwl_destroy will return that status, and if they all succeed it will return 0 for success.

■ rwlock.c part 2 rwl_destroy

1 /*

2 * Destroy a read/write lock.

3 */

4 int rwl_destroy (rwlock_t *rwl)

5 {

6 int status, status1, status2;

7

8 if (rwl->valid != RWLOCK_VALID)

9 return EINVAL;

10 status = pthread_mutex_lock (&rwl->mutex);

11 if (status != 0)

12 return status; 13

14 /*

15 * Check whether any threads own the lock; report "BUSY" if

16 * so.

17 */

18 if (rwl->r_active > 0 || rwl->w_active) {

19 pthread_mutex_unlock (&rwl->mutex);

20 return EBUSY;

21 } 22

23 /*

24 * Check whether any threads are known to be waiting; report

25 * EBUSY if so.

26 */

27 if (rwl->r_wait != 0 || rwl->w_wait != 0) {

28 pthread_mutex_unlock (&rwl->mutex);

29 return EBUSY;

30 } 31

32 rwl->valid = 0;

33 status = pthread_mutex_unlock (&rwl->mutex);

34 if (status != 0)

35 return status;

36 status = pthread_mutex_destroy (&rwl->mutex);

37 status1 = pthread_cond_destroy (&rwl->read);

38 status2 = pthread_cond_destroy (&rwl->write);

39 return (status == 0 ? status

40 : (status1 == 0 ? status1 : status2));

41 }

Part 3 shows the code for rwl_readcleanup and rwl_writecleanup, two cancellation cleanup handlers used in locking the read/write lock for read and write access, respectively. As you may infer from this, read/write locks, unlike barriers, are cancellation points. When a wait is canceled, the waiter needs to decrease the count of threads waiting for either a read or write lock, as appropriate, and unlock the mutex.

■ rwlock.c part 3 cleanuphandlers

1 /*

2 * Handle cleanup when the read lock condition variable

3 * wait is canceled.

4 *

5 * Simply record that the thread is no longer waiting,

6 * and unlock the mutex.

7 */

8 static void rwl_readcleanup (void *arg)

9 {

10 rwlock_t *rwl = (rwlock_t *)arg;

11

12 rwl->r_wait--;

13 pthread_mutex_unlock (&rwl->mutex);

14 }

15

16 /*

17 * Handle cleanup when the write lock condition variable

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

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

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

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

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

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

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

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

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