1 /* Check that Helgrind does not complain about semaphores with a
2    nonzero initial value, when said semaphores are correctly used.
3    Also useful for generating VCG of simple semaphore activity, for
4    inspection. */
5 
6 #include <stdio.h>
7 #include <pthread.h>
8 #include <semaphore.h>
9 #include <assert.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 
13 #define N_THREADS 3
14 
15 static sem_t* my_sem_init(char*, int, unsigned);
16 static int my_sem_destroy(sem_t*);
17 static int my_sem_wait(sem_t*); //static int my_sem_post(sem_t*);
18 
19 void* child_fn ( void* semV ) {
20    int r;
21    sem_t* sem = (sem_t*)semV;
22    r= my_sem_wait(sem); assert(!r);
23    return NULL;
24 }
25 
26 int main ( void )
27 {
28    int r, i;
29    sem_t* sem;
30    pthread_t child[N_THREADS];
31 
32    sem= my_sem_init("sem1", 0, N_THREADS); assert(sem);
33 
34    for (i = 0; i < N_THREADS; i++) {
35       r= pthread_create( &child[i], NULL, child_fn, sem );
36       assert(!r);
37    }
38 
39    for (i = 0; i < N_THREADS; i++) {
40       r= pthread_join( child[i], NULL );
41       assert(!r);
42    }
43 
44    r= my_sem_destroy(sem); assert(!r);
45    return 0;
46 }
47 
48 
49 static sem_t* my_sem_init (char* identity, int pshared, unsigned count)
50 {
51    sem_t* s;
52 
53 #if defined(VGO_linux) || defined(VGO_solaris)
54    s = malloc(sizeof(*s));
55    if (s) {
56       if (sem_init(s, pshared, count) < 0) {
57 	 perror("sem_init");
58 	 free(s);
59 	 s = NULL;
60       }
61    }
62 #elif defined(VGO_darwin)
63    char name[100];
64    sprintf(name, "anonsem_%s_pid%d", identity, (int)getpid());
65    name[ sizeof(name)-1 ] = 0;
66    if (0) printf("name = %s\n", name);
67    s = sem_open(name, O_CREAT | O_EXCL, 0600, count);
68    if (s == SEM_FAILED) {
69       perror("sem_open");
70       s = NULL;
71    }
72 #else
73 #  error "Unsupported OS"
74 #endif
75 
76    return s;
77 }
78 
79 static int my_sem_destroy ( sem_t* s )
80 {
81    return sem_destroy(s);
82 }
83 
84 static int my_sem_wait(sem_t* s)
85 {
86   return sem_wait(s);
87 }
88 
89 #if 0
90 static int my_sem_post(sem_t* s)
91 {
92   return sem_post(s);
93 }
94 #endif
95