diff --git a/src/Lock.h b/src/Lock.h new file mode 100644 index 00000000..2b995721 --- /dev/null +++ b/src/Lock.h @@ -0,0 +1,114 @@ +/* */ +#ifndef D_LOCK_H +#define D_LOCK_H + +#if defined(_WIN32) +#include +#elif defined(ENABLE_PTHREAD) +#include +#endif + + +namespace aria2 { + +class Lock { +private: +#if defined(_WIN32) + ::CRITICAL_SECTION section_; +#elif defined(ENABLE_PTHREAD) + ::pthread_mutex_t mutex_; +#endif + +public: + Lock() { +#if defined(_WIN32) + ::InitializeCriticalSection(§ion_); +#elif defined(ENABLE_PTHREAD) + mutex_ = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; +#endif + } + + ~Lock() { +#if defined(_WIN32) + ::DeleteCriticalSection(§ion_); +#elif defined(ENABLE_PTHREAD) + ::pthread_mutex_destroy(&mutex_); +#endif + } + + inline void aquire() { +#if defined(_WIN32) + ::EnterCriticalSection(§ion_); +#elif defined(ENABLE_PTHREAD) + ::pthread_mutex_lock(&mutex_); +#endif + } + + inline bool tryAquire() { +#if defined(_WIN32) + return ::TryEnterCriticalSection(§ion_) == TRUE; +#elif defined(ENABLE_PTHREAD) + return ::pthread_mutex_trylock(&mutex_) == 0; +#else + return true; +#endif + } + + inline void release() { +#if defined(_WIN32) + ::LeaveCriticalSection(§ion_); +#elif defined(ENABLE_PTHREAD) + ::pthread_mutex_unlock(&mutex_); +#endif + } + +}; + +class LockGuard { +private: + Lock& lock_; +public: + inline LockGuard(Lock& lock) : lock_(lock) { + lock_.aquire(); + } + inline ~LockGuard() { + lock_.release(); + } +}; + +} // namespace aria2 + +#endif // D_LOCK_H diff --git a/src/Makefile.am b/src/Makefile.am index 209ad75f..b9f8edc4 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -250,7 +250,8 @@ SRCS = option_processing.cc\ HttpRequestConnectChain.h\ HttpProxyRequestConnectChain.h\ FtpNegotiationConnectChain.h\ - FtpTunnelRequestConnectChain.h + FtpTunnelRequestConnectChain.h\ + Lock.h # Android NDK R8e does not provide ftruncate64. Use assembly code from # android source code and link it.