aboutsummaryrefslogtreecommitdiff
path: root/helgrind/tests/tc24_nonzero_sem.c
blob: bcd467ccbdf483ca7fba379cc1b5d69505c5322e (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
92
93
94
/* Check that Helgrind does not complain about semaphores with a
   nonzero initial value, when said semaphores are correctly used.
   Also useful for generating VCG of simple semaphore activity, for
   inspection. */

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>

#define N_THREADS 3

static sem_t* my_sem_init(char*, int, unsigned);
static int my_sem_destroy(sem_t*);
static int my_sem_wait(sem_t*); //static int my_sem_post(sem_t*);

void* child_fn ( void* semV ) {
   int r;
   sem_t* sem = (sem_t*)semV;
   r= my_sem_wait(sem); assert(!r);
   return NULL;
}

int main ( void )
{
   int r, i;
   sem_t* sem;
   pthread_t child[N_THREADS];

   sem= my_sem_init("sem1", 0, N_THREADS); assert(sem);

   for (i = 0; i < N_THREADS; i++) {
      r= pthread_create( &child[i], NULL, child_fn, sem );
      assert(!r);
   }

   for (i = 0; i < N_THREADS; i++) {
      r= pthread_join( child[i], NULL );
      assert(!r);
   }

   r= my_sem_destroy(sem); assert(!r);
   return 0;
}


static sem_t* my_sem_init (char* identity, int pshared, unsigned count)
{
   sem_t* s;

#if defined(VGO_linux) || defined(VGO_solaris)
   s = malloc(sizeof(*s));
   if (s) {
      if (sem_init(s, pshared, count) < 0) {
	 perror("sem_init");
	 free(s);
	 s = NULL;
      }
   }
#elif defined(VGO_darwin)
   char name[100];
   sprintf(name, "anonsem_%s_pid%d", identity, (int)getpid());
   name[ sizeof(name)-1 ] = 0;
   if (0) printf("name = %s\n", name);
   s = sem_open(name, O_CREAT | O_EXCL, 0600, count);
   if (s == SEM_FAILED) {
      perror("sem_open");
      s = NULL;
   }
#else
#  error "Unsupported OS"
#endif

   return s;
}

static int my_sem_destroy ( sem_t* s )
{
   return sem_destroy(s);
}

static int my_sem_wait(sem_t* s)
{
  return sem_wait(s);
}

#if 0
static int my_sem_post(sem_t* s)
{
  return sem_post(s);
}
#endif