CcosLock.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. #include "CcosLock.h"
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <map>
  5. #include <atomic>
  6. #include <cerrno> // 包含 ETIMEDOUT 定义
  7. // 进程锁实现
  8. class ProcessLock {
  9. pthread_mutex_t m_Mutex = PTHREAD_MUTEX_INITIALIZER;
  10. pthread_cond_t m_Cond = PTHREAD_COND_INITIALIZER;
  11. bool m_Locked = false;
  12. public:
  13. DWORD Lock(DWORD timeout) {
  14. pthread_mutex_lock(&m_Mutex);
  15. if (!m_Locked) {
  16. m_Locked = true;
  17. pthread_mutex_unlock(&m_Mutex);
  18. return WAIT_OBJECT_0;
  19. }
  20. if (timeout == 0) {
  21. pthread_mutex_unlock(&m_Mutex);
  22. return WAIT_TIMEOUT;
  23. }
  24. struct timespec ts;
  25. if (timeout != INFINITE) {
  26. clock_gettime(CLOCK_REALTIME, &ts);
  27. ts.tv_sec += timeout / 1000;
  28. ts.tv_nsec += (timeout % 1000) * 1000000;
  29. if (ts.tv_nsec >= 1000000000) {
  30. ts.tv_sec++;
  31. ts.tv_nsec -= 1000000000;
  32. }
  33. }
  34. while (m_Locked) {
  35. int ret = (timeout == INFINITE)
  36. ? pthread_cond_wait(&m_Cond, &m_Mutex)
  37. : pthread_cond_timedwait(&m_Cond, &m_Mutex, &ts);
  38. if (ret == ETIMEDOUT) { // 现在 ETIMEDOUT 已定义
  39. pthread_mutex_unlock(&m_Mutex);
  40. return WAIT_TIMEOUT;
  41. }
  42. }
  43. m_Locked = true;
  44. pthread_mutex_unlock(&m_Mutex);
  45. return WAIT_OBJECT_0;
  46. }
  47. void Unlock() {
  48. pthread_mutex_lock(&m_Mutex);
  49. m_Locked = false;
  50. pthread_cond_signal(&m_Cond);
  51. pthread_mutex_unlock(&m_Mutex);
  52. }
  53. };
  54. static ProcessLock g_ProcessLock;
  55. // 全局数据结构
  56. static pthread_mutex_t g_MapMutex = PTHREAD_MUTEX_INITIALIZER;
  57. static std::map<UINT64, DWORD> g_LockedMap; // 对象 -> 线程ID
  58. static std::map<UINT64, CcosLock*> g_ObjectMap; // 对象指针映射
  59. // 注册/注销锁对象
  60. void RegisterLock(CcosLock* p) {
  61. pthread_mutex_lock(&g_MapMutex);
  62. g_ObjectMap[reinterpret_cast<UINT64>(p)] = p;
  63. pthread_mutex_unlock(&g_MapMutex);
  64. }
  65. void UnregisterLock(CcosLock* p) {
  66. pthread_mutex_lock(&g_MapMutex);
  67. UINT64 key = reinterpret_cast<UINT64>(p);
  68. g_ObjectMap.erase(key);
  69. g_LockedMap.erase(key);
  70. pthread_mutex_unlock(&g_MapMutex);
  71. }
  72. // CcosLock 成员函数实现
  73. CcosLock::CcosLock() {
  74. pthread_mutex_init(&m_Mutex, nullptr);
  75. pthread_cond_init(&m_Cond, nullptr);
  76. RegisterLock(this);
  77. }
  78. CcosLock::~CcosLock() {
  79. UnregisterLock(this);
  80. pthread_mutex_destroy(&m_Mutex);
  81. pthread_cond_destroy(&m_Cond);
  82. }
  83. bool CcosLock::CcosInternal_EnterCriticalSection(DWORD TryCount) {
  84. const DWORD tid = GetCurrentThreadId();
  85. DWORD expected = 0;
  86. // 尝试获取锁
  87. if (__atomic_compare_exchange_n(&m_InterLock, &expected, tid,
  88. false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
  89. m_RefCount = 1;
  90. pthread_mutex_lock(&g_MapMutex);
  91. g_LockedMap[reinterpret_cast<UINT64>(this)] = tid;
  92. pthread_mutex_unlock(&g_MapMutex);
  93. return true;
  94. }
  95. // 检查是否已持有锁
  96. if (expected == tid) {
  97. m_RefCount++;
  98. return true;
  99. }
  100. // 尝试多次获取锁
  101. while (TryCount-- > 0) {
  102. expected = 0;
  103. if (__atomic_compare_exchange_n(&m_InterLock, &expected, tid,
  104. false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
  105. m_RefCount = 1;
  106. pthread_mutex_lock(&g_MapMutex);
  107. g_LockedMap[reinterpret_cast<UINT64>(this)] = tid;
  108. pthread_mutex_unlock(&g_MapMutex);
  109. return true;
  110. }
  111. usleep(1000); // 1ms 延迟
  112. }
  113. return false;
  114. }
  115. void CcosLock::CcosInternal_LeaveCriticalSection() {
  116. const DWORD tid = GetCurrentThreadId();
  117. if (m_InterLock == tid) {
  118. if (--m_RefCount == 0) {
  119. pthread_mutex_lock(&g_MapMutex);
  120. g_LockedMap.erase(reinterpret_cast<UINT64>(this));
  121. pthread_mutex_unlock(&g_MapMutex);
  122. __atomic_store_n(&m_InterLock, 0, __ATOMIC_RELEASE);
  123. }
  124. }
  125. }
  126. DWORD CcosLock::Thread_Lock(DWORD timeout) {
  127. if (CcosInternal_EnterCriticalSection(1)) {
  128. return WAIT_OBJECT_0;
  129. }
  130. const DWORD start = GetTickCount();
  131. while (true) {
  132. const DWORD elapsed = GetTickCount() - start;
  133. if (timeout != INFINITE && elapsed >= timeout) {
  134. return WAIT_TIMEOUT;
  135. }
  136. const DWORD remaining = (timeout == INFINITE) ? 100 : (timeout - elapsed);
  137. const DWORD waitTime = std::min<DWORD>(remaining, 100);
  138. const DWORD ret = Thread_WaitUnlockNotify(waitTime);
  139. if (ret == WAIT_OBJECT_0 && CcosInternal_EnterCriticalSection(1)) {
  140. return WAIT_OBJECT_0;
  141. }
  142. }
  143. }
  144. void CcosLock::Thread_UnLock() {
  145. CcosInternal_LeaveCriticalSection();
  146. }
  147. bool CcosLock::Thread_Clear(DWORD tid) {
  148. if (m_InterLock == tid) {
  149. m_RefCount = 0;
  150. pthread_mutex_lock(&g_MapMutex);
  151. g_LockedMap.erase(reinterpret_cast<UINT64>(this));
  152. pthread_mutex_unlock(&g_MapMutex);
  153. __atomic_store_n(&m_InterLock, 0, __ATOMIC_RELEASE);
  154. pthread_cond_broadcast(&m_Cond);
  155. return true;
  156. }
  157. return false;
  158. }
  159. DWORD CcosLock::Thread_WaitUnlockNotify(DWORD timeout) {
  160. pthread_mutex_lock(&m_Mutex);
  161. struct timespec ts;
  162. if (timeout != INFINITE) {
  163. clock_gettime(CLOCK_REALTIME, &ts);
  164. ts.tv_sec += timeout / 1000;
  165. ts.tv_nsec += (timeout % 1000) * 1000000;
  166. if (ts.tv_nsec >= 1000000000) {
  167. ts.tv_sec++;
  168. ts.tv_nsec -= 1000000000;
  169. }
  170. }
  171. while (m_InterLock != 0) {
  172. int ret = (timeout == INFINITE)
  173. ? pthread_cond_wait(&m_Cond, &m_Mutex)
  174. : pthread_cond_timedwait(&m_Cond, &m_Mutex, &ts);
  175. if (ret == ETIMEDOUT) break; // 现在 ETIMEDOUT 已定义
  176. }
  177. pthread_mutex_unlock(&m_Mutex);
  178. return (m_InterLock == 0) ? WAIT_OBJECT_0 : WAIT_TIMEOUT;
  179. }
  180. int CcosLock::FindProcessThreads(DWORD tid) {
  181. return IsThreadAlive(tid);
  182. }
  183. bool CcosLock::Try_Clear_DeadThread() {
  184. return (m_InterLock != 0 && !FindProcessThreads(m_InterLock))
  185. ? Thread_Clear(m_InterLock) : false;
  186. }
  187. // 全局清理函数
  188. void CleanupForThread(DWORD tid) {
  189. pthread_mutex_lock(&g_MapMutex);
  190. auto it = g_LockedMap.begin();
  191. while (it != g_LockedMap.end()) {
  192. if (it->second == tid) {
  193. if (g_ObjectMap.find(it->first) != g_ObjectMap.end()) {
  194. g_ObjectMap[it->first]->Thread_Clear(tid);
  195. }
  196. it = g_LockedMap.erase(it);
  197. } else {
  198. ++it;
  199. }
  200. }
  201. pthread_mutex_unlock(&g_MapMutex);
  202. }
  203. // C接口函数实现
  204. bool Ccos_ThreadLock(volatile UINT64 *pLock) {
  205. volatile DWORD* lockPtr = reinterpret_cast<volatile DWORD*>(pLock);
  206. const DWORD tid = GetCurrentThreadId();
  207. DWORD expected = 0;
  208. if (__atomic_compare_exchange_n(lockPtr, &expected, tid,
  209. false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
  210. lockPtr[1] = 1; // refcount
  211. return true;
  212. }
  213. if (expected == tid) {
  214. lockPtr[1]++; // 增加引用计数
  215. return true;
  216. }
  217. return false;
  218. }
  219. void Ccos_ThreadUnLock(volatile UINT64 *pLock) {
  220. volatile DWORD* lockPtr = reinterpret_cast<volatile DWORD*>(pLock);
  221. const DWORD tid = GetCurrentThreadId();
  222. if (lockPtr[0] == tid) {
  223. if (--lockPtr[1] == 0) { // 减少引用计数
  224. __atomic_store_n(lockPtr, 0, __ATOMIC_RELEASE);
  225. }
  226. }
  227. }
  228. void Ccos_ThreadClearForTid(volatile UINT64 *pLock, DWORD tid) {
  229. volatile DWORD* lockPtr = reinterpret_cast<volatile DWORD*>(pLock);
  230. if (lockPtr[0] == tid) {
  231. lockPtr[1] = 0; // 重置引用计数
  232. __atomic_store_n(lockPtr, 0, __ATOMIC_RELEASE);
  233. }
  234. }
  235. DWORD Proc_Lock(DWORD timeout) {
  236. return g_ProcessLock.Lock(timeout);
  237. }
  238. void Proc_UnLock() {
  239. g_ProcessLock.Unlock();
  240. }
  241. DWORD Thread_GetUniqTick() {
  242. static std::atomic<DWORD> counter(1);
  243. return counter.fetch_add(1, std::memory_order_relaxed);
  244. }