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

81  printf ("Continuing thread %d.\n", i);

82  status = thd_continue (threads[i]);

83  if (status != 0)

84  err_abort (status, "Continue thread");

85  }

86

87 pthread_exit (NULL); /* Let threads finish */

88 }

■ susp.c part 5 sampleprogram

<p>6.6.4 sigwait and sigwaitinfo</p>

int sigwait (const sigset_t *set, int *sig);

#ifdef _POSIX_REALTIME_SIGNALS

int sigwaitinfo (const sigset_t *set, siginfo_t *info);

int sigtimedwait (const sigset_t *set, siginfo_t *info, const struct timespec *timeout);

#endif

Always use sigwait to work with asynchronous signals within threaded code.

Pthreads adds a function to allow threaded programs to deal with "asynchronous" signals synchronously. That is, instead of allowing a signal to interrupt a thread at some arbitrary point, a thread can choose to receive a signal synchronously. It does this by calling sigwait, or one of sigwait's siblings.

The signals for which you sigwait must be masked in the sigwaiting thread,and should usually be masked in all threads.

The sigwait function takes a signal set as its argument, and returns a signal number when any signal in that set occurs. You can create a thread that waits for some signal, for example, SIGINT, and causes some application activity when it occurs. The non-obvious rule is that the signals for which you wait must be masked before calling sigwait. In fact, you should ideally mask these signals in main, at the start of the program. Because signal masks are inherited by threads you create, all threads will (by default) have the signal masked. This ensures that the signal will never be delivered to any thread except the one that calls sigwait.

Signals are delivered only once. If two threads are blocked in sigwait, only one of them will receive a signal that's sent to the process. This means you can't, for example, have two independent subsystems using sigwait that catch SIGINT. It also means that the signal will not be caught by sigwait in one thread and also delivered to some signal-catching function in another thread. That's not so bad, since you couldn't do that in the old nonthreaded model either — only one signal action can be active at a time.

While sigwait, a Pthreads function, reports errors by returning an error number, its siblings, sigwaitinfo and sigtimedwait, were added to POSIX prior to Pthreads, and use the older errno mechanism. This is confusing and awkward, and that is unfortunate. The problem is that they deal with the additional information supplied by the POSIX realtime signals option ( defines the symbol _POSIX_REALTIME_SIGNALS), and the POSIX realtime amendment, POSIX.1b, was completed before the Pthreads amendment.

Both sigwaitinfo and sigtimedwait return the realtime signal information, siginfo_t, for signals received. In addition, sigtimedwait allows the caller to specify that sigtimedwait should return with the error EAGAIN in the event that none of the selected signals is received within the specified interval.

The sigwait.c program creates a "sigwait thread" that handles SIGINT.

23-41 The signal_waiter thread repeatedly calls sigwait, waiting for a SIGINT signal. It counts five occurrences of SIGINT (printing a message each time), and then signals a condition variable on which main is waiting. At that time, main will exit.

61-65 The main program begins by masking SIGINT. Because all threads inherit their initial signal mask from their creator, SIGINT will be masked in all threads. This prevents SIGINT from being delivered at any time except when the signal_ waiter thread is blocked in sigwait and ready to receive the signal.

sigwait.c

1 #include

2 #include

3 #include

4 #include

5 #include "errors.h"

6

7 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

8 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

9 int interrupted = 0;

10 sigset_t signal set;

12 /*

13 * Wait for the SIGINT signal. When it has occurred 5 times, set the

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

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

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

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

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

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

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

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

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