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

Make the calling thread ready, after other ready threads of the same priority, and select a new thread to run. This can allow cooperating threads of the same priority to share processor resources more equitably, especially on a uniprocessor. This function is from POSIX.1b (realtime extensions), and is declared in . It reports errors by setting the return value to -1 and storing an error code in errno.

References: 2, 5.2.3 Headers: 

Errors: [ENOSYS] sched_yield not supported.

Hint: Use before locking mutex to reduce chances of a timeslice while mu-

tex is locked.

<p>9.3.4 Mutexes</p>

Mutexes provide synchronization, the ability to control how threads share resources. You use mutexes to prevent multiple threads from modifying shared data at the same time, and to ensure that a thread can read consistent values for a set of resources (for example, memory) that may be modified by other threads.

pthread_mutexattr_destroy

int pthread_mutexattr_destroy (

pthread_mutexattr_t *attr);

Destroy a mutex attributes object. The object can no longer be used.

References: 3.2, 5.2.1

Headers: 

Errors: [EINVAL]attrinvalid.

Hint: Does not affect mutexes created using attr.

pthread_mutexattr_getpshared..............................................[_POSIX_THREAD_PROCESS_SHARED]

int pthread_mutexattr_getpshared (

const pthread_mutexattr_t *attr,

int *pshared);

Determine whether mutexes created with attr can be shared by multiple processes.

pshared

PTHREAD_PROCESS_SHARED

PTHREAD_PROCESS_PRIVATE

May be shared if in shared memory.

Cannot be shared.

References: 3.2,5.2.1

Headers: 

Errors: [EINVAL]attrinvalid.

Hint: pshared mutexes must be allocated in shared memory.

pthread_mutexattr_init

int pthread_mutexattr_init (

pthread_mutexattr_t *attr);

Initialize a mutex attributes object with default attributes.

References: 3.2,5.2.1

Headers: 

Errors: [ENOMEM] insufficient memory for attr.

Hint: Use to define mutex types.

pthread_mutexattr_setpshared...............................................[_POSIX_THREAD_PROCESS_sHARED ]

int pthread_mutexattr_setpshared (

pthread_mutexattr_t *attr,

int pshared);

Mutexes created with attr can be shared between processes if the pthread_mutex_t variable is allocated in memory shared by the processes.

pshared

PTHREAD_PROCESS_SHARED

May be shared if in shared memory.

PTHREAD_PROCESS_PRIVATE

Cannot be shared.

References: 3.2,5.2.1

Headers: 

Errors: [EINVAL] attr or detachstate invalid.

Hint: pshared mutexes must be allocated in shared memory.

pthread_mutex_destroy

int pthread_mutex_destroy (

pthread_mutex_t *mutex);

Destroy a mutex that you no longer need.

References: 3.2,5.2.1

Headers: 

Errors: [EBUSY] mutex is in use.

[EINVAL] mutex is invalid. Hint: Safest after unlocking mutex, when no other threads will lock.

pthread_mutex_init

int pthread_mutex_init ( pthread_mutex_t const pthread_mutexattr_t

*mutex, *attr);

Initialize a mutex. The attr argument specifies optional creation attributes.

References:

Headers:

Errors:

Hint:

3.2, 5.2.1

[EAGAIN] insufficient resources (other than memory).

[ENOMEM] insufficient memory.

[EPERM] no privilege to perform operation.

[EBUSY] mutex is already initialized.

[EINVAL] attr is invalid.

Use static initialization instead, if possible.

pthread_mutex_lock

int pthread_mutex_lock (

pthread_mutex_t *mutex);

Lock a mutex. If the mutex is currently locked, the calling thread is blocked until mutex is unlocked. On return, the thread owns the mutex until it calls pthread_ mutex_unlock.

References: 3.2, 5.2.1 Headers: 

Errors: [EINVAL] thread priority exceeds mutex priority ceiling.

[EINVAL] mutex is invalid.

[EDEADLK] calling thread already owns mutex. Hint: Always unlock within the same thread.

pthread_mutex_trylock

int pthread_mutex_trylock (

pthread_mutex_t *mutex);

Lock a mutex. If the mutex is currently locked, returns immediately with EBUSY. Otherwise, calling thread becomes owner until it unlocks.

References: 3.2,5.2.1 Headers: 

Errors: [EINVAL] thread priority exceeds mutex priority ceiling.

[EBUSY] mutex is already locked.

[EINVAL] mutex is invalid.

[EDEADLK] calling thread already owns mutex. Hint: Always unlock within the same thread.

pthread_mutex_unlock

int pthread_mutex_unlock (

pthread_mutex_t *mutex);

Unlock a mutex. The mutex becomes unowned. If any threads are waiting for the mutex, one is awakened (scheduling policy SCHED_FIFO and SCHED_RR policy waiters are chosen in priority order, then any others are chosen in unspecified order).

References: 3.2, 5.2.1

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

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

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

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

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

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

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

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

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