SST 15.0
Structural Simulation Toolkit
sstmutex.h
1// Copyright 2009-2025 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-2025, 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 SST_CORE_INTERPROCESS_MUTEX_H
13#define SST_CORE_INTERPROCESS_MUTEX_H
14
15#include <sched.h>
16#include <time.h>
17
18namespace SST::Core::Interprocess {
19
20#define SST_CORE_INTERPROCESS_LOCKED 1
21#define SST_CORE_INTERPROCESS_UNLOCKED 0
22
23class SSTMutex
24{
25
26public:
27 SSTMutex() { lockVal = SST_CORE_INTERPROCESS_UNLOCKED; }
28
29 void processorPause(int currentCount)
30 {
31 if ( currentCount < 64 ) {
32#if defined(__x86_64__)
33 __asm__ __volatile__("pause" : : : "memory");
34#elif (defined(__arm__) || defined(__aarch64__))
35 __asm__ __volatile__("yield");
36#else
37 // Put some pause code in here
38#endif
39 }
40 else if ( currentCount < 256 ) {
41 sched_yield();
42 }
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 {
55 int loop_counter = 0;
56
57 while (
58 !__sync_bool_compare_and_swap(&lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED) ) {
59 processorPause(loop_counter);
60 loop_counter++;
61 }
62 }
63
64 void unlock()
65 {
66 lockVal = SST_CORE_INTERPROCESS_UNLOCKED;
67 __sync_synchronize();
68 }
69
70 bool try_lock()
71 {
72 return __sync_bool_compare_and_swap(&lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED);
73 }
74
75private:
76 volatile int lockVal;
77};
78
79} // namespace SST::Core::Interprocess
80
81#endif // SST_CORE_INTERPROCESS_MUTEX_H