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

Signals that are not "tied" to a specific hardware execution context are delivered to one arbitrary thread within the process. That means a SIGCHLD raised by a child process termination, for example, may not be delivered to the thread that created the child. Similarly, a call to kill results in a signal that may be delivered to any thread.

6.6.1 Signal actions

Thread 1Thread 2Comments
sigaction(SIGFPE)Thread 1's signal action active.
sigaction(SIGFPE) Thread 2's signal action active.
Generate SIGFPEThread 1 signal is handled by the thread 2 signal action (but still in the context of thread 1).
Restore actionThread 1 restores original signal action
restore actionThread 2 restores thread 1 's signal action-original action is lost

FIGURE 6.1Nonmodularity of signal actions

The synchronous "hardware context" signals, including SIGFPE, SIGSEGV, and SIGTRAP, are delivered to the thread that caused the hardware condition, never to another thread.

You cannot kill a thread by sending it a SIGKILL or stop a thread by sending it a SIGSTOR

Any signal that affected a process still affects the process when multiple threads are active, which means that sending a SIGKILL to a process or to any specific thread in the process (using pthread_kill, which we'll get to in Section 6.6.3) will terminate the process. Sending a SIGSTOP will cause all threads to stop until a SIGCONT is received. This ensures that existing process control functions continue to work — otherwise most threads in a process could continue running when you stopped a command by sending a SIGSTOP. This also applies to the default action of the other signals, for example, SIGSEGV, if not handled, will terminate the process and generate a core file — it will not terminate only the thread that generated the SIGSEGV.

What does this mean to a programmer? It has always been common wisdom that library code should not change signal actions — that this is exclusively the province of the main program. This philosophy becomes even more wise when you are programming with threads. Signal actions must always be under the control of a single component, at least, and to assign that responsibility to the main program makes the most sense in nearly all situations.

<p>6.6.2 Signal masks</p>

int pthread_sigmask (int how, const sigset_t *set, sigset_t *oset);

Each thread has its own private signal mask, which is modified by calling pthread_sigmask. Pthreads does not specify what sigprocmask does within a threaded process — it may do nothing. Portable threaded code does not call sigprocmask. A thread can block or unblock signals without affecting the ability of other threads to handle the signal. This is particularly important for synchronous signals. It would be awkward if thread A were unable to process a SIGFPE because thread B was currently processing its own SIGFPE or. even worse, because thread C had blocked SIGFPE. When a thread is created, it inherits the signal mask of the thread that created it — if you want a signal to be masked everywhere, mask it first thing in main.

<p>6.6.3 pthread_kill</p>

int pthread_kill (pthread_t thread, int sig);

Within a process, one thread can send a signal to a specific thread (including itself) by calling pthread_kill. When calling pthread_kill, you specify not only the signal number to be delivered, but also the pthread_t identifier for the thread to which you want the signal sent. You cannot use pthread_kill to send a signal to a thread in another process, however, because a thread identifier (pthread_t) is meaningful only within the process that created it.

The signal sent by pthread_kill is handled like any other signal. If the "target" thread has the signal masked, it will be marked pending against that thread. If the thread is waiting for the signal in sigwait (covered in Section 6.6.4), the thread will receive the signal. If the thread does not have the signal masked, and is not blocked in sigwait, the current signal action will be taken.

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

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

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

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

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

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

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

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

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