CcosLock.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. #include "CcosLock.h"
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <map>
  5. #include <iostream>
  6. #include <stdexcept>
  7. // 进程锁实现
  8. class ProcessLock {
  9. pthread_mutex_t m_Mutex = PTHREAD_MUTEX_INITIALIZER;
  10. pthread_cond_t m_Cond = PTHREAD_COND_INITIALIZER;
  11. std::atomic<bool> m_Locked{ false };
  12. public:
  13. DWORD Lock(DWORD timeout) {
  14. if (pthread_mutex_lock(&m_Mutex) != 0) {
  15. throw std::runtime_error("Failed to lock process mutex");
  16. }
  17. if (!m_Locked) {
  18. m_Locked = true;
  19. pthread_mutex_unlock(&m_Mutex);
  20. return WAIT_OBJECT_0;
  21. }
  22. if (timeout == 0) {
  23. pthread_mutex_unlock(&m_Mutex);
  24. return WAIT_TIMEOUT;
  25. }
  26. struct timespec ts;
  27. if (timeout != INFINITE) {
  28. clock_gettime(CLOCK_REALTIME, &ts);
  29. ts.tv_sec += timeout / 1000;
  30. ts.tv_nsec += (timeout % 1000) * 1000000;
  31. if (ts.tv_nsec >= 1000000000) {
  32. ts.tv_sec++;
  33. ts.tv_nsec -= 1000000000;
  34. }
  35. }
  36. int ret = 0;
  37. while (m_Locked && ret == 0) {
  38. ret = (timeout == INFINITE)
  39. ? pthread_cond_wait(&m_Cond, &m_Mutex)
  40. : pthread_cond_timedwait(&m_Cond, &m_Mutex, &ts);
  41. }
  42. if (ret == ETIMEDOUT) {
  43. pthread_mutex_unlock(&m_Mutex);
  44. return WAIT_TIMEOUT;
  45. }
  46. m_Locked = true;
  47. pthread_mutex_unlock(&m_Mutex);
  48. return WAIT_OBJECT_0;
  49. }
  50. void Unlock() {
  51. if (pthread_mutex_lock(&m_Mutex) != 0) {
  52. throw std::runtime_error("Failed to lock process mutex");
  53. }
  54. m_Locked = false;
  55. pthread_cond_signal(&m_Cond);
  56. pthread_mutex_unlock(&m_Mutex);
  57. }
  58. };
  59. ProcessLock& GetProcessLock() {
  60. static ProcessLock instance;
  61. return instance;
  62. }
  63. pthread_mutex_t& GetMapMutex() {
  64. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  65. return mutex;
  66. }
  67. std::map<UINT64, DWORD>& GetLockedMap() {
  68. static std::map<UINT64, DWORD> instance;
  69. return instance;
  70. }
  71. std::map<UINT64, CcosLock*>& GetObjectMap() {
  72. static std::map<UINT64, CcosLock*> instance;
  73. return instance;
  74. }
  75. // 注册/注销锁对象
  76. void RegisterLock(CcosLock* p) {
  77. pthread_mutex_lock(&GetMapMutex());
  78. GetObjectMap()[reinterpret_cast<UINT64>(p)] = p;
  79. pthread_mutex_unlock(&GetMapMutex());
  80. }
  81. void UnregisterLock(CcosLock* p) {
  82. pthread_mutex_lock(&GetMapMutex());
  83. UINT64 key = reinterpret_cast<UINT64>(p);
  84. GetObjectMap().erase(key);
  85. GetLockedMap().erase(key);
  86. pthread_mutex_unlock(&GetMapMutex());
  87. }
  88. // CcosLock 成员函数实现
  89. CcosLock::CcosLock() {
  90. if (pthread_mutex_init(&m_Mutex, nullptr) != 0) {
  91. throw std::runtime_error("Failed to initialize mutex");
  92. }
  93. if (pthread_cond_init(&m_Cond, nullptr) != 0) {
  94. pthread_mutex_destroy(&m_Mutex);
  95. throw std::runtime_error("Failed to initialize condition variable");
  96. }
  97. RegisterLock(this);
  98. }
  99. CcosLock::~CcosLock() {
  100. m_IsDestroyed = true;
  101. UnregisterLock(this);
  102. // 等待所有等待线程唤醒后再销毁
  103. pthread_mutex_lock(&m_Mutex);
  104. pthread_cond_broadcast(&m_Cond);
  105. pthread_mutex_unlock(&m_Mutex);
  106. pthread_mutex_destroy(&m_Mutex);
  107. pthread_cond_destroy(&m_Cond);
  108. }
  109. bool CcosLock::CcosInternal_EnterCriticalSection(DWORD TryCount) {
  110. const DWORD tid = GetCurrentThreadId();
  111. DWORD expected = 0;
  112. // 尝试获取锁
  113. if (m_InterLock.compare_exchange_strong(expected, tid,
  114. std::memory_order_acq_rel,
  115. std::memory_order_relaxed)) {
  116. m_RefCount = 1;
  117. pthread_mutex_lock(&GetMapMutex());
  118. GetLockedMap()[reinterpret_cast<UINT64>(this)] = tid;
  119. pthread_mutex_unlock(&GetMapMutex());
  120. return true;
  121. }
  122. // 检查是否已持有锁
  123. if (expected == tid) {
  124. m_RefCount++;
  125. return true;
  126. }
  127. // 尝试多次获取锁
  128. while (TryCount-- > 0) {
  129. expected = 0;
  130. if (m_InterLock.compare_exchange_strong(expected, tid,
  131. std::memory_order_acq_rel,
  132. std::memory_order_relaxed)) {
  133. m_RefCount = 1;
  134. pthread_mutex_lock(&GetMapMutex());
  135. GetLockedMap()[reinterpret_cast<UINT64>(this)] = tid;
  136. pthread_mutex_unlock(&GetMapMutex());
  137. return true;
  138. }
  139. usleep(1000); // 1ms 延迟
  140. }
  141. return false;
  142. }
  143. void CcosLock::CcosInternal_LeaveCriticalSection() {
  144. const DWORD tid = GetCurrentThreadId();
  145. const DWORD current_tid = m_InterLock.load(std::memory_order_acquire);
  146. if (current_tid == tid) {
  147. if (--m_RefCount == 0) {
  148. // 清除锁状态前获取全局映射锁
  149. pthread_mutex_lock(&GetMapMutex());
  150. GetLockedMap().erase(reinterpret_cast<UINT64>(this));
  151. pthread_mutex_unlock(&GetMapMutex());
  152. m_InterLock.store(0, std::memory_order_release);
  153. // 通知等待的线程
  154. pthread_mutex_lock(&m_Mutex);
  155. pthread_cond_broadcast(&m_Cond);
  156. pthread_mutex_unlock(&m_Mutex);
  157. }
  158. }
  159. else {
  160. std::cerr << "Thread " << tid << " attempted to unlock lock owned by " << current_tid << std::endl;
  161. }
  162. }
  163. DWORD CcosLock::Thread_Lock(DWORD timeout) {
  164. if (IsDestroyed()) return WAIT_TIMEOUT;
  165. if (CcosInternal_EnterCriticalSection(1)) {
  166. return WAIT_OBJECT_0;
  167. }
  168. const DWORD start = GetTickCount();
  169. while (!IsDestroyed()) {
  170. const DWORD elapsed = GetTickCount() - start;
  171. if (timeout != INFINITE && elapsed >= timeout) {
  172. return WAIT_TIMEOUT;
  173. }
  174. const DWORD remaining = (timeout == INFINITE) ? 100 : (timeout - elapsed);
  175. const DWORD waitTime = std::min<DWORD>(remaining, 100);
  176. const DWORD ret = Thread_WaitUnlockNotify(waitTime);
  177. if (ret == WAIT_OBJECT_0 && CcosInternal_EnterCriticalSection(1)) {
  178. return WAIT_OBJECT_0;
  179. }
  180. }
  181. return WAIT_TIMEOUT;
  182. }
  183. void CcosLock::Thread_UnLock() {
  184. if (!IsDestroyed()) {
  185. CcosInternal_LeaveCriticalSection();
  186. }
  187. }
  188. bool CcosLock::Thread_Clear(DWORD tid) {
  189. if (m_InterLock == tid) {
  190. m_RefCount = 0;
  191. pthread_mutex_lock(&GetMapMutex());
  192. GetLockedMap().erase(reinterpret_cast<UINT64>(this));
  193. pthread_mutex_unlock(&GetMapMutex());
  194. m_InterLock.store(0, std::memory_order_release);
  195. pthread_cond_broadcast(&m_Cond);
  196. return true;
  197. }
  198. return false;
  199. }
  200. DWORD CcosLock::Thread_WaitUnlockNotify(DWORD timeout) {
  201. if (IsDestroyed()) return WAIT_TIMEOUT;
  202. pthread_mutex_lock(&m_Mutex);
  203. struct timespec ts;
  204. if (timeout != INFINITE) {
  205. clock_gettime(CLOCK_REALTIME, &ts);
  206. ts.tv_sec += timeout / 1000;
  207. ts.tv_nsec += (timeout % 1000) * 1000000;
  208. if (ts.tv_nsec >= 1000000000) {
  209. ts.tv_sec++;
  210. ts.tv_nsec -= 1000000000;
  211. }
  212. }
  213. int ret = 0;
  214. while (m_InterLock != 0 && ret == 0 && !IsDestroyed()) {
  215. ret = (timeout == INFINITE)
  216. ? pthread_cond_wait(&m_Cond, &m_Mutex)
  217. : pthread_cond_timedwait(&m_Cond, &m_Mutex, &ts);
  218. }
  219. pthread_mutex_unlock(&m_Mutex);
  220. if (IsDestroyed()) return WAIT_TIMEOUT;
  221. return (m_InterLock == 0) ? WAIT_OBJECT_0 : WAIT_TIMEOUT;
  222. }
  223. int CcosLock::FindProcessThreads(DWORD tid) {
  224. return IsThreadAlive(tid) ? 1 : 0;
  225. }
  226. bool CcosLock::Try_Clear_DeadThread() {
  227. return (m_InterLock != 0 && !FindProcessThreads(m_InterLock))
  228. ? Thread_Clear(m_InterLock) : false;
  229. }
  230. // 全局清理函数
  231. void CleanupForThread(DWORD tid) {
  232. pthread_mutex_lock(&GetMapMutex());
  233. auto it = GetLockedMap().begin();
  234. while (it != GetLockedMap().end()) {
  235. if (it->second == tid) {
  236. if ( GetObjectMap().find(it->first) != GetObjectMap().end()) {
  237. GetObjectMap()[it->first]->Thread_Clear(tid);
  238. }
  239. it = GetLockedMap().erase(it);
  240. } else {
  241. ++it;
  242. }
  243. }
  244. pthread_mutex_unlock(&GetMapMutex());
  245. }
  246. // C接口函数实现
  247. bool Ccos_ThreadLock(ThreadLock *pLock) {
  248. if (!pLock) return false;
  249. const DWORD tid = GetCurrentThreadId();
  250. DWORD expected = 0;
  251. if (pLock->thread_id.compare_exchange_strong(expected, tid,
  252. std::memory_order_acq_rel,
  253. std::memory_order_relaxed)) {
  254. pLock->ref_count = 1;
  255. return true;
  256. }
  257. if (expected == tid) {
  258. pLock->ref_count++;
  259. return true;
  260. }
  261. return false;
  262. }
  263. void Ccos_ThreadUnLock(ThreadLock* pLock) {
  264. if (!pLock) return;
  265. const DWORD tid = GetCurrentThreadId();
  266. if (pLock->thread_id == tid) {
  267. if (--pLock->ref_count == 0) {
  268. pLock->thread_id.store(0, std::memory_order_release);
  269. }
  270. }
  271. }
  272. void Ccos_ThreadClearForTid(ThreadLock* pLock, DWORD tid) {
  273. if (!pLock) return;
  274. if (pLock->thread_id == tid) {
  275. pLock->ref_count = 0;
  276. pLock->thread_id.store(0, std::memory_order_release);
  277. }
  278. }
  279. DWORD Proc_Lock(DWORD timeout) {
  280. return GetProcessLock().Lock(timeout);
  281. }
  282. void Proc_UnLock() {
  283. GetProcessLock().Unlock();
  284. }
  285. DWORD Thread_GetUniqTick() {
  286. static std::atomic<DWORD> counter(1);
  287. return counter.fetch_add(1, std::memory_order_relaxed);
  288. }