SST  7.0.0
StructuralSimulationToolkit
sstmutex.h
1 
2 
3 #ifndef _H_SST_CORE_INTERPROCESS_MUTEX
4 #define _H_SST_CORE_INTERPROCESS_MUTEX
5 
6 #include <sched.h>
7 #include <time.h>
8 
9 namespace SST {
10 namespace Core {
11 namespace Interprocess {
12 
13 #define SST_CORE_INTERPROCESS_LOCKED 1
14 #define SST_CORE_INTERPROCESS_UNLOCKED 0
15 
16 class SSTMutex {
17 
18 public:
19  SSTMutex() {
20  lockVal = SST_CORE_INTERPROCESS_UNLOCKED;
21  }
22 
23  void processorPause(int currentCount) {
24  if( currentCount < 64 ) {
25 #if defined(__x86_64__)
26  asm volatile ("pause" : : : "memory");
27 #else
28  // Put some pause code in here
29 #endif
30  } else if( currentCount < 256 ) {
31  sched_yield();
32  } else {
33  struct timespec sleepPeriod;
34  sleepPeriod.tv_sec = 0;
35  sleepPeriod.tv_nsec = 100;
36 
37  struct timespec interPeriod;
38  nanosleep(&sleepPeriod, &interPeriod);
39  }
40  }
41 
42  void lock() {
43  int loop_counter = 0;
44 
45  while( ! __sync_bool_compare_and_swap( &lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED) ) {
46  processorPause(loop_counter);
47  loop_counter++;
48  }
49  }
50 
51  void unlock() {
52  lockVal = SST_CORE_INTERPROCESS_UNLOCKED;
53  __sync_synchronize();
54  }
55 
56  bool try_lock() {
57  return __sync_bool_compare_and_swap( &lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED );
58  }
59 
60 private:
61  volatile int lockVal;
62 
63 };
64 
65 }
66 }
67 }
68 
69 #endif
Definition: action.cc:17
Definition: sstmutex.h:16