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

18 * wait is canceled.

19 *

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

21 * and unlock the mutex.

22 */

23 static void rwl_writecleanup (void *arg)

24 {

25 rwlock_t *rwl = (rwlock_t *)arg;

26

27 rwl->w_wait--;

28 pthread_mutex_unlock (&rwl->mutex);

29 }

10-26 Part 4 shows rwl_readlock, which locks a read/write lock for read access. If a writer is currently active (w_active is nonzero), we wait for it to broadcast the read condition variable. The r_wait member counts the number of threads waiting to read. This could be a simple boolean variable, except for one problem— when a waiter is canceled, we need to know whether there are any remaining waiters. Maintaining a count makes this easy, since the cleanup handler only needs to decrease the count.

This is one of the places where the code must be changed to convert our read/ write lock from "reader preference" to "writer preference," should you choose to do that. To implement writer preference, a reader must block while there are waiting writers (w_wait > 0), not merely while there are active writers, as we do here.

15-21 Notice the use of the cleanup handler around the condition wait. Also, notice that we pass the argument 0 to pthread_cleanup_pop so that the cleanup code is called only if the wait is canceled. We need to perform slightly different actions when the wait is not canceled. If the wait is not canceled, we need to increase the count of active readers before unlocking the mutex.

■ rwlock.c part 4 rwl_readlock

1 /*

2 * Lock a read/write lock for read access.

3 */

4 int rwl_readlock (rwlock_t *rwl)

5 {

6 int status;

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 if (rwl->w_active) {

14  rwl->r_wait++;

15  pthread_cleanup_push (rwl_readcleanup, (void*)rwl);

16  while (rwl->w_active) {

17  status = pthread_cond_wait (&rwl->read, &rwl->mutex);

18  if (status != 0)

19  break;

20  }

21 pthread_cleanup_pop (0);

22 rwl->r_wait--;

23 }

24 if (status == 0)

25 rwl->r_active++;

26 pthread_mutex_unlock (&rwl->mutex);

27 return status;

28 }

Part 5 shows rwl_readtrylock. This function is nearly identical to rwl_readlock, except that, instead of waiting for access if a writer is active, it returns EBUSY. It doesn't need a cleanup handler, and has no need to increase the count of waiting readers.

This function must also be modified to implement "writer preference" read/ write locks, by returning EBUSY when a writer is waiting, not just when a writer is active.

■ rwlock.c part 5 rwl_readtrylock

1 /*

2 * Attempt to lock a read/write lock for read access (don't

3 * block if unavailable).

4 */

5 int rwl_readtrylock (rwlock_t *rwl)

6 {

7 int status, status2;

8

9 if (rwl->valid != RWLOCK_VALID)

10  return EINVAL;

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

12 if (status != 0)

13  return status;

14 if (rwl->w_active)

15  status = EBUSY;

16 else

17  rwl->r_active++;

18 status2 = pthread_mutex_unlock (&rwl->mutex);

19 return (status2 != 0 ? status2 : status);

20 }

13 Part 6 shows rwl_readunlock. This function essentially reverses the effect of rwl_readlock or rwl_tryreadlock, by decreasing the count of active readers (r_active).

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

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

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

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

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

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

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

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

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