coregrind/m_gdbserver/remote-utils.c (prepare_resume_reply): Use memcpy
[valgrind.git] / drd / tests / annotate_sem.c
blob016e8b588dcec23f0e7675a32867900214d85eb5
1 /**
2 * @file annotate_sem.c
4 * @brief Multithreaded test program that triggers various access patterns
5 * without triggering any race conditions using a binary semaphore
6 * implemented via busy-waiting. Annotations are used to tell DRD
7 * which higher-level semaphore operations are being performed.
8 */
10 #include <assert.h>
11 #include <pthread.h>
12 #include <stdio.h>
13 #include "../../config.h"
14 #include "../../drd/drd.h"
16 #define THREADS 10
17 #define ITERATIONS 1000
19 typedef struct {
20 volatile unsigned value;
21 } sem_t;
23 static sem_t s_sem;
24 static unsigned int s_counter;
26 static void sem_init(sem_t *p, unsigned value)
28 DRD_IGNORE_VAR(*p);
29 p->value = value;
30 ANNOTATE_SEM_INIT_PRE(p, value);
33 static void sem_destroy(sem_t *p)
35 ANNOTATE_SEM_DESTROY_POST(p);
38 static void sem_wait(sem_t *p)
40 unsigned old, new;
41 struct timespec ts = { 0, 0 };
43 ANNOTATE_SEM_WAIT_PRE(p);
44 do {
45 old = p->value;
46 new = old - 1;
47 nanosleep(&ts, NULL);
48 ts.tv_nsec = 1;
49 } while (!old || !__sync_bool_compare_and_swap(&p->value, old, new));
50 ANNOTATE_SEM_WAIT_POST(p);
53 static void sem_post(sem_t *p)
55 ANNOTATE_SEM_POST_PRE(p);
56 __sync_fetch_and_add(&p->value, 1);
59 static void *thread_func(void *arg)
61 unsigned int i;
62 unsigned int sum = 0;
64 for (i = 0; i < ITERATIONS; i++) {
65 sem_wait(&s_sem);
66 sum += s_counter;
67 sem_post(&s_sem);
69 sem_wait(&s_sem);
70 s_counter++;
71 sem_post(&s_sem);
74 return 0;
77 int main(int argc, const char *argv[])
79 pthread_t tid[THREADS];
80 unsigned int i;
82 sem_init(&s_sem, 1);
83 for (i = 0; i < THREADS; i++)
84 pthread_create(&tid[i], 0, thread_func, 0);
86 for (i = 0; i < THREADS; i++)
87 pthread_join(tid[i], 0);
89 assert(s_counter == THREADS * ITERATIONS);
90 assert(s_sem.value == 1);
91 sem_destroy(&s_sem);
93 fprintf(stderr, "Finished.\n");
95 return 0;