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

The POSIX standard distinguishes carefully between two categories of error:

1. Mandatory ("if occurs") errors involve circumstances beyond the control of the programmer. These errors must always be detected and reported by the system using a particular error code. If you cannot create a new thread because your process lacks sufficient virtual memory, then the implementation must always tell you. You can't possibly be expected to check whether there's enough memory before creating the thread—for one thing, you have no way to know how much memory would be required.

2. Optional ("if detected") errors are problems that are usually your mistake. You might try to lock a mutex that hadn't been initialized, for example, or try to unlock a mutex that's locked by another thread. Some systems may

not detect these errors, but they're still errors in your code, and you ought to be able to avoid them without help from the system.

While it would be "nice" for the system to detect optional errors and return the appropriate error number, sometimes it takes a lot of time to check or is difficult to check reliably. It may be expensive, for example, for the system to determine the identity of the current thread. Systems may therefore not remember which thread locked a mutex, and would be unable to detect that the unlock was erroneous. It may not make sense to slow down the basic synchronization operations for correct programs just to make it a little easier to debug incorrect programs.

Systems may provide debugging modes where some or all of the optional errors are detected. Digital UNIX, for example, provides "error check" mutexes and a "metered" execution mode, where the ownership of mutexes is always tracked and optional errors in locking and unlocking mutexes are reported. The UNLX98 specification includes "error check" mutexes (Section 10.1.2), so they will soon be available on most UNIX systems.

<p>9.3.2 Use of void* type</p>

ANSI C requires that you be allowed to convert any pointer type to void* and back, with the result being identical to the original value. However, ANSI C does not require that all pointer types have the same binary representation. Thus, a long* that you convert to void* in order to pass into a thread's start routine must always be used as a long*, not as, for example, a char*. In addition, the result of converting between pointer and integer types is "implementation defined." Most systems supporting UNIX will allow you to cast an integer value to void* and back, and to mix pointer types — but be aware that the code may not work on all systems.

Some other standards, notably the POSIX. lb realtime standard, have solved the same problem (the need for an argument or structure member that can take any type value) in different ways. The sigevent structure in POSIX.1b, for example, includes a member that contains a value to be passed into a signal-catching function, called sigev_value. Instead of defining sigev_value as a void*, however, and relying on the programmer to provide proper type casting, the sigev_ value member is a union sigval, containing overlayed int and void* members. This mechanism avoids the problem of converting between integer and pointer types, eliminating one of the conflicts with ANSI C guarantees.

<p>9.3.3 Threads</p>

Threads provide concurrency, the ability to have more than one "stream of execution" within a process at the same time. Each thread has its own hardware registers and stack. All threads in a process share the full virtual address space, plus all file descriptors, signal actions, and other process resources.

pthread_attr_destroy

int pthread_attr_destroy (

pthread_attr_t *attr);

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

References: 2, 5.2.3

Headers: 

Errors: [EINVAL]attr is invalid.

Hint: Does not affect threads created using attr.

pthread_attr_getdetachstate

int pthread_attr_getdetachstate (

const pthread_attr_t *attr, int *detachstate);

Determine whether threads created with attr will run detached

detachstate

PTHREAD CREATE JOINABLE

PTHREAD CREATE DETACHED

Thread ID is valid, must be joined.

Thread ID is invalid, cannot be joined, canceled, or modified.

References: 2, 5.2.3

Headers: 

Errors: [EINVAL] attr is invalid.

Hint: You can't join or cancel detached threads.

pthread_attr_getstackaddr.....................................................[_POSIX_THREAD_ATTR_STACKADDR]

int pthread_attr_getstackaddr (

const pthread_attr_t *attr,

void **stackaddr);

Determine the address of the stack on which threads created with attr will run.

References: 2, 5.2.3

Headers: 

Errors: [EINVAL]attrisinvalid.

[ENOSYS] stacksize not supported. Hint: Create only one thread for each stack address!

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

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

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

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

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

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

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

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

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