GRASS GIS 7 Programmer's Manual  7.9.dev(2021)-e5379bbd7
counter.c
Go to the documentation of this file.
1 #include <grass/config.h>
2 #ifdef HAVE_PTHREAD_H
3 #define _XOPEN_SOURCE 500
4 #endif
5 #include <grass/gis.h>
6 
7 #ifdef HAVE_PTHREAD_H
8 #include <pthread.h>
9 static pthread_mutex_t mutex;
10 #endif
11 
12 #ifdef HAVE_PTHREAD_H
13 static void make_mutex(void)
14 {
15  static pthread_mutex_t t_mutex = PTHREAD_MUTEX_INITIALIZER;
16  static int initialized;
17  pthread_mutexattr_t attr;
18 
19  if (initialized)
20  return;
21 
22  pthread_mutex_lock(&t_mutex);
23 
24  if (initialized) {
25  pthread_mutex_unlock(&t_mutex);
26  return;
27  }
28 
29  pthread_mutexattr_init(&attr);
30  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
31  pthread_mutex_init(&mutex, &attr);
32  initialized = 1;
33 
34  pthread_mutex_unlock(&t_mutex);
35 }
36 #endif
37 
38 void G_init_counter(struct Counter *c, int v)
39 {
40 #ifdef HAVE_PTHREAD_H
41  make_mutex();
42 #endif
43  c->value = v;
44 }
45 
46 int G_counter_next(struct Counter *c)
47 {
48  int v;
49 #ifdef HAVE_PTHREAD_H
50  pthread_mutex_lock(&mutex);
51 #endif
52  v = c->value++;
53 #ifdef HAVE_PTHREAD_H
54  pthread_mutex_unlock(&mutex);
55 #endif
56  return v;
57 }
58 
59 int G_is_initialized(int *p)
60 {
61  if (*p)
62  return 1;
63 
64 #ifdef HAVE_PTHREAD_H
65  make_mutex();
66  pthread_mutex_lock(&mutex);
67 
68  if (*p) {
69  pthread_mutex_unlock(&mutex);
70  return 1;
71  }
72 #endif
73  return 0;
74 }
75 
76 void G_initialize_done(int *p)
77 {
78  *p = 1;
79 
80 #ifdef HAVE_PTHREAD_H
81  pthread_mutex_unlock(&mutex);
82 #endif
83 }
84 
void G_init_counter(struct Counter *c, int v)
Definition: counter.c:38
Definition: gis.h:593
int G_is_initialized(int *p)
Definition: counter.c:59
void G_initialize_done(int *p)
Definition: counter.c:76
int value
Definition: gis.h:594
int G_counter_next(struct Counter *c)
Definition: counter.c:46