tlds
Transactional Operations for Linked Data Structures
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
barrier.hpp
Go to the documentation of this file.
1 /**
2  * Copyright (C) 2011
3  * University of Rochester Department of Computer Science
4  * and
5  * Lehigh University Department of Computer Science and Engineering
6  *
7  * License: Modified BSD
8  * Please see the file LICENSE.RSTM for licensing information
9  */
10 
11 /* barrier.hpp
12  *
13  * Simple barrier. Currently based on pthread locks.
14  * Note that pthread barriers are an optional part of the standard, and
15  * are not supported on some platforms (including my mac).
16  * If verbose, prints time when barrier is achieved.
17  */
18 
19 #ifndef BARRIER_HPP__
20 #define BARRIER_HPP__
21 
22 #include <pthread.h> // for pthread_cond_t and pthread_mutex_t
23 #include <string>
24  using std::string;
25 
26 #include "macros.hpp"
27 
28 class barrier {
30  int parity; // for sense reversal
31  pthread_mutex_t mutex;
32  int count[2];
33  pthread_cond_t sem[2];
34 public:
35  void wait(string s) {
36  VERIFY(pthread_mutex_lock(&mutex));
37  int my_parity = parity;
38  ++count[my_parity];
39  if (count[my_parity] == participants) {
40  // I was the last to arrive
41  count[my_parity] = 0;
42  parity = 1 - my_parity;
43 
44  if (verbose && s.size() != 0) {
45  unsigned long long now = getElapsedTime();
46  {
47  with_lock cs(io_lock);
48  cout << "time: " << (now - start_time)/1e9 << " "
49  << (now - last_time)/1e9
50  << " (" << s << ")\n";
51  }
52  last_time = now;
53  }
54  VERIFY(pthread_cond_broadcast(&sem[my_parity]));
55  } else {
56  while (!count[my_parity] == 0) {
57  VERIFY(pthread_cond_wait(&sem[my_parity], &mutex));
58  }
59  }
60  VERIFY(pthread_mutex_unlock(&mutex));
61  }
62  barrier(int n) : participants(n) {
63  count[0] = count[1] = 0;
64  parity = 0;
65  VERIFY(pthread_mutex_init(&mutex, 0));
66  VERIFY(pthread_cond_init(&sem[0], 0));
67  VERIFY(pthread_cond_init(&sem[1], 0));
68  }
70  VERIFY(pthread_mutex_destroy(&mutex));
71  VERIFY(pthread_cond_destroy(&sem[0]));
72  VERIFY(pthread_cond_destroy(&sem[1]));
73  }
74 };
75 
76 #endif // BARRIER_HPP__
int count[2]
Definition: barrier.hpp:32
unsigned long long start_time
Definition: mesh.cpp:34
pthread_cond_t sem[2]
Definition: barrier.hpp:33
bool verbose
Definition: mesh.cpp:44
pthread_mutex_t mutex
Definition: barrier.hpp:31
#define VERIFY(E)
Definition: macros.hpp:25
~barrier()
Definition: barrier.hpp:69
void wait(string s)
Definition: barrier.hpp:35
Definition: barrier.hpp:28
d_lock io_lock
Definition: mesh.cpp:33
Definition: lock.hpp:46
int parity
Definition: barrier.hpp:30
barrier(int n)
Definition: barrier.hpp:62
int participants
Definition: barrier.hpp:29
unsigned long long last_time
Definition: mesh.cpp:35