SST 12.1.0
Structural Simulation Toolkit
sstmutex.h
1// Copyright 2009-2022 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-2022, 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 {
19namespace Core {
20namespace Interprocess {
21
22#define SST_CORE_INTERPROCESS_LOCKED 1
23#define SST_CORE_INTERPROCESS_UNLOCKED 0
24
26{
27
28public:
29 SSTMutex() { lockVal = SST_CORE_INTERPROCESS_UNLOCKED; }
30
31 void processorPause(int currentCount)
32 {
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 }
42 else if ( currentCount < 256 ) {
43 sched_yield();
44 }
45 else {
46 struct timespec sleepPeriod;
47 sleepPeriod.tv_sec = 0;
48 sleepPeriod.tv_nsec = 100;
49
50 struct timespec interPeriod;
51 nanosleep(&sleepPeriod, &interPeriod);
52 }
53 }
54
55 void lock()
56 {
57 int loop_counter = 0;
58
59 while (
60 !__sync_bool_compare_and_swap(&lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED) ) {
61 processorPause(loop_counter);
62 loop_counter++;
63 }
64 }
65
66 void unlock()
67 {
68 lockVal = SST_CORE_INTERPROCESS_UNLOCKED;
69 __sync_synchronize();
70 }
71
72 bool try_lock()
73 {
74 return __sync_bool_compare_and_swap(&lockVal, SST_CORE_INTERPROCESS_UNLOCKED, SST_CORE_INTERPROCESS_LOCKED);
75 }
76
77private:
78 volatile int lockVal;
79};
80
81} // namespace Interprocess
82} // namespace Core
83} // namespace SST
84
85#endif // SST_CORE_INTERPROCESS_MUTEX_H
Definition: sstmutex.h:26