summaryrefslogtreecommitdiff
path: root/drd/tests/rwlock_test.c
blob: b8dcf471f4572178b5bebdf9c5d946b64a204e44 (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
/**
 * @file  rwlock_test.c
 *
 * @brief Multithreaded test program that triggers various access patterns
 *        without triggering any race conditions.
 */


#define _GNU_SOURCE 1

#include <pthread.h>
#include <stdio.h>


static pthread_rwlock_t s_rwlock;
static int s_counter;

static void* thread_func(void* arg)
{
  int i;
  int sum = 0;

  for (i = 0; i < 1000; i++)
  {
    pthread_rwlock_rdlock(&s_rwlock);
    sum += s_counter;
    pthread_rwlock_unlock(&s_rwlock);
    pthread_rwlock_wrlock(&s_rwlock);
    s_counter++;
    pthread_rwlock_unlock(&s_rwlock);
  }

  return 0;
}

int main(int argc, char** argv)
{
  const int thread_count = 10;
  pthread_t tid[thread_count];
  int i;

  pthread_rwlock_init(&s_rwlock, NULL);
  for (i = 0; i < thread_count; i++)
  {
    pthread_create(&tid[i], 0, thread_func, 0);
  }

  for (i = 0; i < thread_count; i++)
  {
    pthread_join(tid[i], 0);
  }

  fprintf(stderr, "Finished.\n");

  return 0;
}