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

65  printf ("(%d) %s\n", alarm->seconds, alarm->message);

66  free (alarm);

67 }

68 }

69 }

And finally, the code for the main program for alarm_mutex.c. The basic structure is the same as all of the other versions of the alarm program that we've developed—a loop, reading simple commands from stdin and processing each in turn. This time, instead of waiting synchronously as in alarm.c, or creating a new asynchronous entity to process each alarm command as in alarm_fork.c and alarm_thread.c, each request is queued to a server thread, alarm_thread. As soon as main has queued the request, it is free to read the next command.

8-11 Create the server thread that will process all alarm requests. Although we don't use it, the thread's ID is returned in local variable thread.

13-28 Read and process a command, much as in any of the other versions of our alarm program. As in alarm_thread.c, the data is stored in a heap structure allocated by malloc.

30-32 The program needs to add the alarm request to alarm_list, which is shared by both alarm_thread and main. So we start by locking the mutex that synchronizes access to the shared data, alarm_mutex.

33 Because alarm_thread processes queued requests, serially, it has no way of knowing how much time has elapsed between reading the command and processing it. Therefore, the alarm structure includes the absolute time of the alarm expiration, which we calculate by adding the alarm interval, in seconds, to the

current number of seconds since the UNIX Epoch, as returned by the time function.

39-49 The alarms are sorted in order of expiration time on the alarm_list queue. The insertion code searches the queue until it finds the first entry with a time greater than or equal to the new alarm's time. The new entry is inserted preceding the located entry. Because alarm_list is a simple linked list, the traversal maintains a current entry pointer (this) and a pointer to the previous entry's link member, or to the alarm_list head pointer (last).

56-59 If no alarm with a time greater than or equal to the new alarm's time is found, then the new alarm is inserted at the end of the list. That is, if the alarm pointer is NULL on exit from the search loop (the last entry on the list always has a link pointer of NULL), the previous entry (or queue head) is made to point to the new entry.

alarm_mutex.c part 3 main

1 int main (int argc, char *argv[])

2 {

3 int status;

4 char line[128];

5 alarm_t *alarm, **last, *next;

6 pthread_t thread;

7

8 status = pthread_create (

9 &thread, NULL, alarm_thread, NULL);

10 if (status != 0)

11 err_abort (status, "Create alarm thread");

12 while (1) {

13  printf ("alarm> ");

14  if (fgets (line, sizeof (line), stdin) == NULL) exit (0);

15  if (strlen (line) <= 1) continue;

16  alarm = (alarm_t*)malloc (sizeof (alarm_t));

17  if (alarm == NULL)

18  errno_abort ("Allocate alarm");

19

20 /*

21 * Parse input line into seconds (%d) and a message

22 * (%64[^\n]), consisting of up to 64 characters

23 * separated from the seconds by whitespace.

24 */

25  if (sscanf (line, "%d %64[^\n]",

26  &alarm->seconds, alarm->message) < 2) {

27  fprintf (stderr, "Bad command\n");

28  free (alarm);

29  } else {

30  status = pthread_mutex_lock (&alarm_mutex);

31  if (status != 0)

32  err_abort (status, "Lock mutex");

33  alarm->time = time (NULL) + alarm->seconds;

34

35 /*

36 * Insert the new alarm into the list of alarms,

37 * sorted by expiration time.

38 */

39  last = &alarm_list;

40  next = *last;

41  while (next != NULL) {

42  if (next->time >= alarm->time) {

43  alarm->link = next;

44  *last = alarm;

45  break;

46  }

47  last = &next->link;

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

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

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

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

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

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

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

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

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