Created
September 27, 2019 12:19
-
-
Save leetking/149d73d7d444962b3db01a6b1ce833bf to your computer and use it in GitHub Desktop.
implement auto lock and unlock via a simple using way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <climits> | |
#include <cctype> | |
#include <cmath> | |
#include <cstring> | |
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
#include <set> | |
#include <map> | |
#include <queue> | |
using namespace std; | |
#define ARR_SIZE(x) ((int)sizeof(x)/sizeof(x[0])) | |
#ifndef NDEBUG /* fllow the macor `NDEBUG` from assert.h */ | |
# define _D(...) printf(__VA_ARGS__) | |
#else | |
# define _D(...) ((void)0) | |
#endif | |
class Lock { | |
private: | |
pthread_mutex_t *lock; | |
public: | |
Lock(pthread_mutex_t &mutex) { | |
lock = &mutex; | |
pthread_mutex_lock(lock); | |
} | |
~Lock() { | |
pthread_mutex_unlock(lock); | |
} | |
}; | |
#define lock1(lk) if (Lock(lk), 1) | |
#define lock2(lk) \ | |
for (int __quit__ = 0; \ | |
!__quit__ && (pthread_mutex_lock(lk), 1); \ | |
__quit__ = 1, pthread_mutex_unlock(lk)) | |
int main(int argc, char **argv) | |
{ | |
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; | |
lock1(mutex) { | |
printf("use lock with c++ style\n"); | |
} | |
lock2(&mutex) { | |
printf("use lock with c style\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment