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

[EINVAL] different mutexes for concurrent waits. [EINVAL] mutex is not owned by calling thread.

Hint: Mutex is always unlocked (before wait) and relocked (after wait) in-

side pthread_cond_wait, even if the wait fails or is canceled.

<p>9.3.6 Cancellation</p>

Cancellation provides a way to request that a thread terminate "gracefully" when you no longer need it to complete its normal execution. Each thread can control how and whether cancellation affects it, and can repair the shared state as it terminates due to cancellation.

pthread_cancel

int pthread_cancel (

pthread_t thread);

Requests that thread be canceled.

References: 5.3 Headers: 

Errors: [ESRCH] no thread found corresponding to thread.

Hint: Cancellation is asynchronous. Use pthread_join to wait for termi-

nation of thread if necessary.

pthread_cleanup_pop

void pthread_cleanup_pop (int execute);

Pop the most recently pushed cleanup handler. Invoke the cleanup handler if execute is nonzero.

References: 5.3 Headers: 

Hint: Specify execute as nonzero to avoid duplication of common cleanup

code.

pthread_cleanup_push

void pthread_cleanup_push (

void (*routine)(void *),

void *arg);

Push a new cleanup handler onto the thread's stack of cleanup handlers. Invoke the cleanup handler if execute is nonzero. Each cleanup handler pushed onto the stack is popped and invoked with the argument arg when the thread exits by calling pthread_exit, when the thread acts on a cancellation request, or when the thread calls pthread_cleanup_pop with a nonzero execute argument.

References: 5.3 Headers: 

Hint: pthread_cleanup_push and pthread_cleanup_pop must be paired

in the same lexical scope.

pthread_setcancelstate

int pthread_setcancelstate (

int state,

int *oldstate);

Atomically set the calling thread's cancelability state to state and return the previous cancelability state at the location referenced by oldstate.

state, oldstate

PTHREAD_CANCEL_ENABLE

Cancellation is enabled.

PTHREAD_CANCEL_DISABLE

Cancellatlon is disabled.

References: 5.3

Headers: 

Errors: [EINVAL]stateisinvalid.

Hint: Use to disable cancellation around "atomic" code that includes can-

cellation points.

pthread_setcanceltype

int pthread_setcanceltype (

int type,

int *oldtype);

Atomically set the calling thread's cancelability type to type and return the previous cancelability type at the location referenced by oldtype.

type, oldtype

PTHREAD_CANCEL_DEFERRED

Only deferred cancellation is allowed.

PTHREAD_CANCEL_ASYNCHRONOUS Asynchronous cancellation is

allowed.

References: 5.3

Headers: 

Errors: [EINVAL] type is invalid.

Hint: Use with caution — most code is not safe for use with asynchronous

cancelability type.

pthread_testcancel

void pthread_testcancel (void);

Creates a deferred cancellation point in the calling thread. The call has no effect if the current cancelability state is PTHREAD_CANCEL_DISABLE.

References: 5.3 Headers: 

Hint: Cancellation is asynchronous. Use pthread_join to wait for termi-

nation of thread if necessary.

<p>9.3.7 Thread-specific data</p>

Thread-specific data provides a way to declare variables that have a common "name" in all threads, but a unique value in each thread. You should consider using thread-speciflc data in a threaded program in many cases where a non-threaded program would use "static" data. When the static data maintains context across a series of calls to some function, for example, the context should generally be thread-specific. (If not, the static data must be protected by a mutex.)

pthread_getspecific

void *pthread_getspecific (

pthread_key_t key);

Return the current value of key in the calling thread. If no value has been set for key in the thread, NULL is returned.

References: 5.4, 7.2, 7.3.1 Headers: 

Errors: The effect of calling pthread_getspecific with an invalid key is un-

defined. No errors are detected.

Hint: Calling pthread_getspecific in a destructor function will return

NULL. Use destructor's argument instead.

pthread_key_create

int pthread_key_create (

pthread_key_t *key,

void (*destructor)(void *));

Create a thread-specific data key visible to all threads. All existing and new threads have value NULL for key until set using pthread_setspecific. When any thread with a non-NULL value for key terminates, destructor is called with key's current value for that thread.

References: 5.4,7.2,7.3.1 Headers: 

Errors: [EAGAIN] insufficientresourcesorPTHREAD_KEYS_MAxexceeded.

[ENOMEM] insufficient memory to create the key. Hint: Each key (pthread_key_t variable) must be created only once; use

a mutex or pthread_once.

pthread_key_delete

int pthread_key_delete (

pthread_key_t key);

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

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

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

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

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

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

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

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

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