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

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 || rwl->r_active > 0)

15  status = EBUSY;

16 else

17  rwl->w_active = 1;

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

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

20 }

Finally, part 9 shows rwl_writeunlock. This function is called by a thread with a write lock, to release the lock.

13-19 When a writer releases the read/write lock, it is always free; if there are any threads waiting for access, we must wake one. Because we implement "preferred read" access, we first look for threads that are waiting for read access. If there are any, we broadcast the read condition variable to wake them all.

20-26 If there were no waiting readers, but there are one or more waiting writers, wake one of them by signaling the write condition variable.

To implement a "preferred write" lock, you would reverse the two tests, waking a waiting writer, if any, before looking for waiting readers.

■ rwlock.c part 9 rwl_writeunlock

1 /*

2 * Unlock a read/write lock from write access.

3 */

4 int rwl_writeunlock (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 rwl->w_active = 0;

14 if (rwl->r_wait > 0) {

15  status = pthread_cond_broadcast(&rwl->read);

16  if (status != 0) {

17  pthread_mutex_unlock (&rwl->mutex);

18  return status;

19 }

20 } else if (rwl->w_wait > 0) {

21  status = pthread_cond_signal (&rwl->write);

22  if (status != 0) {

23  pthread_mutex_unlock (&rwl->mutex);

24  return status;

25  }

26 }

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

28 return status;

29 }

■ rwlock.c part 9 writelock

Now that we have all the pieces, rwlock_main.c shows a program that uses read/write locks.

11-17 Each thread is described by a structure of type thread_t. The thread_num member is the thread's index within the array of thread_t structures. The thread_id member is the pthread_t (thread identifier) returned by pthread_ create when the thread was created. The updates and reads members are counts of the number of read lock and write lock operations performed by the thread. The interval member is generated randomly as each thread is created, to determine how many iterations the thread will read before it performs a write.

22-26 The threads cycle through an array of data_t elements. Each element has a read/write lock, a data element, and a count of how many times some thread has updated the element.

48-58 The program creates a set of threads running the thread_routine function. Each thread loops ITERATIONS times, practicing use of the read/write lock. It cycles through the array of data elements in sequence, resetting the index (element) to 0 when it reaches the end. At intervals specified by each thread's interval member, the thread will modify the current data element instead of reading it. The thread locks the read/write lock for write access, stores its thread_num as the new data value, and increases the updates counter.

59-73 On all other iterations, thread_routine reads the current data element, locking the read/write lock for read access. It compares the data value against its thread_num to determine whether it was the most recent thread to update that data element, and, if so, it increments a counter.

95-103 On Solaris systems, increase the thread concurrency level to generate more interesting activity. Without timeslicing of user threads, each thread would tend to execute sequentially otherwise.

rwlock_main.c

1 #include "rwlock.h"

2 #include "errors.h"

3

4 #define THREADS 5

5 #define DATASIZE 15

6 #define ITERATIONS 10000

7

8 /*

9 * Keep statistics for each thread.

10 */

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

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

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

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

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

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

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

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

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