SST  9.0.0
StructuralSimulationToolkit
sstmutex.h
1 // Copyright 2009-2019 NTESS. Under the terms
2 // of Contract DE-NA0003525 with NTESS, the U.S.
3 // Government retains certain rights in this software.
4 //
5 // Copyright (c) 2009-2019, NTESS
6 // All rights reserved.
7 //
8 // This file is part of the SST software package. For license
9 // information, see the LICENSE file in the top level directory of the
10 // distribution.
11 
12 #ifndef _H_SST_CORE_INTERPROCESS_MUTEX
13 #define _H_SST_CORE_INTERPROCESS_MUTEX
14 
15 #include <sched.h>
16 #include <time.h>
17 
18 namespace SST {
19 namespace Core {
20 namespace Interprocess {
21 
22 #define SST_CORE_INTERPROCESS_LOCKED 1
23 #define SST_CORE_INTERPROCESS_UNLOCKED 0
24 
25 class SSTMutex {
26 
27 public:
28  SSTMutex() {
29  lockVal = SST_CORE_INTERPROCESS_UNLOCKED;
30  }
31 
32  void processorPause(int currentCount) {
33  if( currentCount < 64 ) {
34 #if defined(__x86_64__)
35  asm volatile ("pause" : : : "memory");
36 #else
37  // Put some pause code in here
38 #endif
39  } else if( currentCount < 256 ) {
40  sched_yield();
41  } else {
42  struct timespec sleepPeriod;
43  sleepPeriod.tv_sec = 0;
44  sleepPeriod.tv_nsec = 100;
45 
46  struct timespec interPeriod;
47  nanosleep(&sleepPeriod, &interPeriod);
48  }
49  }
50 
51  void lock() {
52  int loop_counter = 0;
53 
54  while( ! __sync_bool_compare_and_swap( &lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED) ) {
55  processorPause(loop_counter);
56  loop_counter++;
57  }
58  }
59 
60  void unlock() {
61  lockVal = SST_CORE_INTERPROCESS_UNLOCKED;
62  __sync_synchronize();
63  }
64 
65  bool try_lock() {
66  return __sync_bool_compare_and_swap( &lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED );
67  }
68 
69 private:
70  volatile int lockVal;
71 
72 };
73 
74 }
75 }
76 }
77 
78 #endif
Definition: sstmutex.h:25