about summary refs log tree commit diff
path: root/nptl/cond-perf.c
blob: c3305b391d8f8a26a406eaa12d32cd900873a208 (plain) (blame)
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
95
96
97
98
99
100
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER;

static pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER;

static bool last_round;
static int ntogo;
static bool alldone;


static void *
cons (void *arg)
{
  pthread_mutex_lock (&mut1);

  do
    {
      if (--ntogo == 0)
	{
	  alldone = true;
	  pthread_cond_signal (&cond2);
	}

      pthread_cond_wait (&cond1, &mut1);
    }
  while (! last_round);

  pthread_mutex_unlock (&mut1);

  return NULL;
}


int
main (int argc, char *argv[])
{
  int opt;
  int err;
  int nthreads = 10;
  int nrounds = 100;
  bool keeplock = false;

  while ((opt = getopt (argc, argv, "n:r:k")) != -1)
    switch (opt)
      {
      case 'n':
	nthreads = atol (optarg);
	break;
      case 'r':
	nrounds = atol (optarg);
	break;
      case 'k':
	keeplock = true;
	break;
      }

  ntogo = nthreads;

  pthread_t th[nthreads];
  int i;
  for (i = 0; i < nthreads; ++i)
    if ((err = pthread_create (&th[i], NULL, cons, (void *) (long) i)) != 0)
      printf ("pthread_create: %s\n", strerror (err));

  for (i = 0; i < nrounds; ++i)
    {
      pthread_mutex_lock (&mut2);
      while (! alldone)
	pthread_cond_wait (&cond2, &mut2);
      pthread_mutex_unlock (&mut2);

      pthread_mutex_lock (&mut1);
      if (! keeplock)
	pthread_mutex_unlock (&mut1);

      ntogo = nthreads;
      alldone = false;
      if (i + 1 >= nrounds)
	last_round = true;

      pthread_cond_broadcast (&cond1);

      if (keeplock)
	pthread_mutex_unlock (&mut1);
    }

  for (i = 0; i < nthreads; ++i)
    if ((err = pthread_join (th[i], NULL)) != 0)
      printf ("pthread_create: %s\n", strerror (err));

  return 0;
}