summaryrefslogtreecommitdiff
path: root/cleanup.c
blob: 9ea43164422f0c55db638fb57b4f0cab2631df4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
 * cleanup.c
 *
 * Description:
 * This translation unit implements routines associated cleaning up
 * threads.
 */

#include "pthread.h"
#include "implement.h"

void
_pthread_handler_push(_pthread_handler_node_t ** stacktop,
		      int poporder,
		      void (*routine)(void *), 
		      void *arg)
{
  /* Place the new handler into the list so that handlers are
     popped off in the order given by poporder. */
  _pthread_handler_node_t * new;
  _pthread_handler_node_t * next;

  new = (_pthread_handler_node_t *) malloc(sizeof(_pthread_handler_node_t));

  if (new == NULL)
    {
      /* FIXME: INTERNAL ERROR */
    }

  new->routine = routine;
  new->arg = arg;

  if (poporder == _PTHREAD_HANDLER_POP_LIFO)
    {
      /* Add the new node to the start of the list. */
      new->next = *stacktop;
      stacktop = next;
    }
  else
    {
      /* Add the new node to the end of the list. */
      new->next = NULL;

      if (*stacktop == NULL)
	{
	  *stacktop = new;
	}
      else
	{
	  next = *stacktop;
	  while (next != NULL)
	    {
	      next = next->next;
	    }
	  next = new;
	}
    }
}

void
_pthread_handler_pop(_pthread_handler_node_t ** stacktop,
		     int execute)
{
  _pthread_handler_node_t * handler = *stacktop;

  if (handler != NULL)
    {
      void (* func)(void *) = handler->routine;
      void * arg = handler->arg;

      *stacktop = handler->next;

      free(handler);

      if (execute != 0 && func != NULL)
	{
	  (void) func(arg);
	}
    }
}

void
_pthread_handler_pop_all(_pthread_handler_node_t ** stacktop, 
			 int execute)
{
  /* Pop and run all handlers on the given stack. */
  while (*stacktop != NULL)
    {
      _pthread_handler_pop(stacktop, execute);
    }
}