xRedis API  1.5.0
The C++ Client API for Redis server
 All Classes
xLock.h
1 /*
2  * ----------------------------------------------------------------------------
3  * Copyright (c) 2012-2021, xSky <guozhw at gmail dot com>
4  * All rights reserved.
5  * Distributed under GPL license.
6  * ----------------------------------------------------------------------------
7  */
8 
9 #ifndef _XLOCK_H_
10 #define _XLOCK_H_
11 
12 #ifdef _WIN32
13 #include <Windows.h>
14 #else
15 #include <pthread.h>
16 #include <stdio.h>
17 #include <unistd.h>
18 #endif
19 
20 namespace xrc {
21 
22 class xLock {
23 private:
24 #ifdef _WIN32
25  CRITICAL_SECTION mSection;
26 #else
27  pthread_mutex_t mMutex;
28 #endif
29 
30 public:
31  inline xLock()
32  {
33 #ifdef _WIN32
34  InitializeCriticalSection(&mSection);
35 #else
36  pthread_mutexattr_t attr;
37  pthread_mutexattr_init(&attr);
38  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
39  int ret = pthread_mutex_init(&mMutex, &attr);
40  if (ret != 0) {
41  fprintf(stderr, "pthread_mutex_init error %d \n\r", ret);
42  }
43 #endif
44  };
45  inline ~xLock()
46  {
47 #ifdef _WIN32
48  DeleteCriticalSection(&mSection);
49 #else
50  pthread_mutex_destroy(&mMutex);
51 #endif
52  }
53  inline void Enter()
54  {
55 #ifdef _WIN32
56  EnterCriticalSection(&mSection);
57 #else
58  pthread_mutex_lock(&mMutex);
59 #endif
60  }
61  inline void Leave()
62  {
63 #ifdef _WIN32
64  LeaveCriticalSection(&mSection);
65 #else
66  pthread_mutex_unlock(&mMutex);
67 #endif
68  };
69 };
70 
71 class CLockUser {
72 public:
73  inline CLockUser(xLock& lock)
74  : mlock(lock)
75  {
76  mlock.Enter();
77  };
78  inline ~CLockUser()
79  {
80  mlock.Leave();
81  }
82 
83 private:
84  xLock& mlock;
85 };
86 
87 #define XLOCK(T) CLockUser lock(T)
88 
89 } // namespace xrc
90 
91 #endif
Definition: xLock.h:22
Definition: xLock.h:71

Generated on Mon Mar 21 2022 10:57:13 for xRedis API version 1.5.0.