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

2 #include "errors.h"

3

4 pthread_once_t once_block = PTHREAD_ONCE_INIT;

5 pthread_mutex_t mutex;

6

7 /*

8 * This is the one-time initialization routine. It will be

9 * called exactly once, no matter how many calls to pthread_once

10 * with the same control structure are made during the course of

11 * the program.

12 */

13 void once_init_routine (void)

14 {

15  int status;

16

17  status = pthread_mutex_init (&mutex, NULL);

18  if (status != 0)

19  err_abort (status, "Init Mutex");

20 }

21

22 /*

23 * Thread start routine that calls pthread_once.

24 */

25 void *thread_routine (void *arg)

26 {

27  int status;

28

29  status = pthread_once (&once_block, once_init_routine);

30  if (status != 0)

31  err_abort (status, "Once init");

32  status = pthread_mutex_lock (&mutex);

33  if (status != 0)

34  err_abort (status, "Lock mutex");

35  printf ("thread_routine has locked the mutex.\n");

36  status = pthread_mutex_unlock (&mutex);

37  if (status != 0)

38  err_abort (status, "Unlock mutex");

39  return NULL;

40 }

41

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

43 {

44  pthread_t thread_id;

45  char *input, buffer[64];

46  int status;

47

48  status = pthread_create (&thread_id, NULL, thread_routine, NULL);

49  if (status != 0)

50  err_abort (status, "Create thread");

51  status = pthread_once (&once_block, once_init_routine);

52  if (status != 0)

53  err_abort (status, "Once init");

54  status = pthread_mutex_lock (&mutex);

55  if (status != 0)

56  err_abort (status, "Lock mutex");

57  printf ("Main has locked the mutex.\n");

58  status = pthread_mutex_unlock (&mutex);

59  if (status != 0)

60  err_abort (status, "Unlock mutex");

61  status = pthread_join (thread_id, NULL);

62  if (status != 0)

63  err_abort (status, "Join thread");

64  return 0;

65 }

<p>5.2 Attributes objects</p>

The fifth ls ambition. It next will be right

To describe each particular batch:

Distinguishing those that have feathers, and bite,

From those that have whiskers, and scratch.

Lewis Carroll, The Hunting of the Snark

So far, when we created threads, or dynamically initialized mutexes and condition variables, we have usually used the pointer value NULL as the second argument. That argument is actually a pointer to an attributes object. The value NULL indicates that Pthreads should assume the default value for all attributes— just as it does when statically initializing a mutex or condition variable.

An attributes object is an extended argument list provided when you initialize an object. It allows the main interfaces (for example, pthread_create) to be relatively simple, while allowing "expert" capability when you need it. Later POSIX standards will be able to add options without requiring source changes to existing code. In addition to standard attributes provided by Pthreads, an implementation can provide specialized options without creating nonstandard parameters.

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

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

C++: базовый курс
C++: базовый курс

В этой книге описаны все основные средства языка С++ - от элементарных понятий до супервозможностей. После рассмотрения основ программирования на C++ (переменных, операторов, инструкций управления, функций, классов и объектов) читатель освоит такие более сложные средства языка, как механизм обработки исключительных ситуаций (исключений), шаблоны, пространства имен, динамическая идентификация типов, стандартная библиотека шаблонов (STL), а также познакомится с расширенным набором ключевых слов, используемым в .NET-программировании. Автор справочника - общепризнанный авторитет в области программирования на языках C и C++, Java и C# - включил в текст своей книги и советы программистам, которые позволят повысить эффективность их работы. Книга рассчитана на широкий круг читателей, желающих изучить язык программирования С++.

Герберт Шилдт

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