SST  10.1.0
StructuralSimulationToolkit
sstmutex.h
1 // Copyright 2009-2020 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-2020, 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 #elif ( defined(__arm__) || defined(__aarch64__) )
37  __asm__ __volatile__ ("yield");
38 #else
39  // Put some pause code in here
40 #endif
41  } else if( currentCount < 256 ) {
42  sched_yield();
43  } else {
44  struct timespec sleepPeriod;
45  sleepPeriod.tv_sec = 0;
46  sleepPeriod.tv_nsec = 100;
47 
48  struct timespec interPeriod;
49  nanosleep(&sleepPeriod, &interPeriod);
50  }
51  }
52 
53  void lock() {
54  int loop_counter = 0;
55 
56  while( ! __sync_bool_compare_and_swap( &lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED) ) {
57  processorPause(loop_counter);
58  loop_counter++;
59  }
60  }
61 
62  void unlock() {
63  lockVal = SST_CORE_INTERPROCESS_UNLOCKED;
64  __sync_synchronize();
65  }
66 
67  bool try_lock() {
68  return __sync_bool_compare_and_swap( &lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED );
69  }
70 
71 private:
72  volatile int lockVal;
73 
74 };
75 
76 }
77 }
78 }
79 
80 #endif
Definition: sstmutex.h:25