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

The thread_attr.c program that follows shows some of these attributes in action, with proper conditionalization to avoid using the stacksize attribute if it is not supported by your system. If stacksize is supported (and it will be on most UNIX systems), the program will print the default and minimum stack size, and set stacksize to a value twice the minimum. The code also creates the thread detached, which means no thread can join with it to determine when it completes. Instead, main exits by calling pthread_exit, which means that the process will terminate when the last thread exits.

This example does not include the priority scheduling attributes, which are discussed (and demonstrated) in Section 5.5.2. It also does not demonstrate use of the stackaddr attribute — as I said, there is no way to use stackaddr in any remotely portable way and, although I have mentioned it for completeness, I strongly discourage use of stackaddr in any program.

thread_attr.c

1 #include

2 #include

3 #include "errors.h"

4

5 /*

6 * Thread start routine that reports it ran, and then exits.

7 */

8 void *thread_routine (void *arg)

9 {

10  printf ("The thread is here\n");

11  return NULL;

12 }

13

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

15 {

16  pthread_t thread_id;

17  pthread_attr_t thread_attr;

18  struct sched_param thread_param;

19  size_t stack_size;

20  int status;

21

22  status = pthread_attr_init (&thread_attr);

23  if (status != 0)

24  err_abort (status, "Create attr");

25

26 /*

27 * Create a detached thread.

28 */

29  status = pthread_attr_setdetachstate (

30  &thread_attr, PTHREAD_CREATE_DETACHED);

31  if (status != 0)

32  err_abort (status, "Set detach");

33 #ifdef _POSIX_THREAD_ATTR_STACKSIZE

34 /*

35 * If supported, determine the default stack size and report

36 * it, and then select a stack size for the new thread.

37 *

38 * Note that the standard does not specify the default stack

39 * size, and the default value in an attributes object need

40 * not be the size that will actually be used. Solaris 2.5

41 * uses a value of 0 to indicate the default.

42 */

43  status = pthread_attr_getstacksize (&thread_attr, &stack_size);

44  if (status != 0)

45  err_abort (status, "Get stack size");

46  printf ("Default stack size is %u; minimum is %u\n",

47  stack_size, PTHREAD_STACK_MIN);

48  status = pthread_attr_setstacksize (

49  &thread_attr, PTHREAD_STACK_MIN*2);

50  if (status != 0)

51  err_abort (status, "Set stack size");

52 #endif

53  status = pthread_create (

54  &thread_id, &thread_attr, thread_routine, NULL);

55  if (status != 0)

56  err_abort (status, "Create thread");

57  printf ("Main exiting\n");

58  pthread_exit (NULL);

59 return 0;

60 }

<p>5.3 Cancellation</p>

"Now, I give you fair warning,"

shouted the Queen, stamping on the ground as she spoke;

"either you or your head must be off,

and that in about halfno time! Take your choice!"

The Duchess took her choice, and was gone in a moment.

Lewis Carroll,Alice's Adventures in Wonderland
Перейти на страницу:

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

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

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

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

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