Panda3D
reMutexSpinlockImpl.cxx
Go to the documentation of this file.
1 /**
2  * PANDA 3D SOFTWARE
3  * Copyright (c) Carnegie Mellon University. All rights reserved.
4  *
5  * All use of this software is subject to the terms of the revised BSD
6  * license. You should have received a copy of this license along
7  * with this source code in a file named "LICENSE."
8  *
9  * @file reMutexSpinlockImpl.cxx
10  * @author rdb
11  * @date 2018-09-03
12  */
13 
14 #include "selectThreadImpl.h"
15 
16 #ifdef MUTEX_SPINLOCK
17 
18 #include "reMutexSpinlockImpl.h"
19 #include "thread.h"
20 
21 #if defined(__i386__) || defined(__x86_64) || defined(_M_IX86) || defined(_M_X64)
22 #include <emmintrin.h>
23 #define PAUSE() _mm_pause()
24 #else
25 #define PAUSE()
26 #endif
27 
28 /**
29  *
30  */
31 void ReMutexSpinlockImpl::
32 lock() {
33  Thread *current_thread = Thread::get_current_thread();
34  Thread *locking_thread = (Thread *)AtomicAdjust::compare_and_exchange_ptr(_locking_thread, nullptr, current_thread);
35  while (locking_thread != nullptr && locking_thread != current_thread) {
36  PAUSE();
37  locking_thread = (Thread *)AtomicAdjust::compare_and_exchange_ptr(_locking_thread, nullptr, current_thread);
38  }
39  ++_counter;
40 }
41 
42 /**
43  *
44  */
45 bool ReMutexSpinlockImpl::
46 try_lock() {
47  Thread *current_thread = Thread::get_current_thread();
48  Thread *locking_thread = (Thread *)AtomicAdjust::compare_and_exchange_ptr(_locking_thread, nullptr, current_thread);
49  if (locking_thread == nullptr || locking_thread == current_thread) {
50  ++_counter;
51  return true;
52  } else {
53  return false;
54  }
55 }
56 
57 #undef PAUSE
58 
59 #endif // MUTEX_SPINLOCK
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.
get_current_thread
Returns a pointer to the currently-executing Thread object.
Definition: thread.h:109
A thread; that is, a lightweight process.
Definition: thread.h:46
static Pointer compare_and_exchange_ptr(Pointer &mem, Pointer old_value, Pointer new_value)
Atomic compare and exchange.
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.