| 1 | // | 
|---|---|
| 2 | // Mutex_STD.cpp | 
| 3 | // | 
| 4 | // Library: Foundation | 
| 5 | // Package: Threading | 
| 6 | // Module: Mutex | 
| 7 | // | 
| 8 | // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. | 
| 9 | // and Contributors. | 
| 10 | // | 
| 11 | // SPDX-License-Identifier: BSL-1.0 | 
| 12 | // | 
| 13 | |
| 14 | |
| 15 | #include "Poco/Mutex_STD.h" | 
| 16 | #include "Poco/Timestamp.h" | 
| 17 | #include <thread> | 
| 18 | |
| 19 | |
| 20 | namespace Poco { | 
| 21 | |
| 22 | |
| 23 | MutexImpl::MutexImpl(MutexTypeImpl type) | 
| 24 | : _mutex(type == MUTEX_RECURSIVE_IMPL ? | 
| 25 | std::unique_ptr<MutexImpl_BaseMutex>(new MutexImpl_MutexI<std::recursive_timed_mutex>()) : | 
| 26 | std::unique_ptr<MutexImpl_BaseMutex>(new MutexImpl_MutexI<std::timed_mutex>())) | 
| 27 | { | 
| 28 | } | 
| 29 | |
| 30 | |
| 31 | bool MutexImpl::tryLockImpl(long milliseconds) | 
| 32 | { | 
| 33 | const int sleepMillis = 5; | 
| 34 | Timestamp now; | 
| 35 | Timestamp::TimeDiff diff(Timestamp::TimeDiff(milliseconds)*1000); | 
| 36 | |
| 37 | do | 
| 38 | { | 
| 39 | try | 
| 40 | { | 
| 41 | if (_mutex->tryLock(milliseconds)) | 
| 42 | return true; | 
| 43 | } | 
| 44 | catch (...) | 
| 45 | { | 
| 46 | throw SystemException( "cannot lock mutex"); | 
| 47 | } | 
| 48 | std::this_thread::sleep_for(std::chrono::milliseconds(sleepMillis)); | 
| 49 | } while (!now.isElapsed(diff)); | 
| 50 | return false; | 
| 51 | } | 
| 52 | |
| 53 | |
| 54 | FastMutexImpl::FastMutexImpl() : _mutex() | 
| 55 | { | 
| 56 | } | 
| 57 | |
| 58 | |
| 59 | bool FastMutexImpl::tryLockImpl(long milliseconds) | 
| 60 | { | 
| 61 | const int sleepMillis = 5; | 
| 62 | Timestamp now; | 
| 63 | Timestamp::TimeDiff diff(Timestamp::TimeDiff(milliseconds)*1000); | 
| 64 | do | 
| 65 | { | 
| 66 | try | 
| 67 | { | 
| 68 | if (_mutex.try_lock_for(std::chrono::milliseconds(milliseconds))) | 
| 69 | return true; | 
| 70 | } | 
| 71 | catch (...) | 
| 72 | { | 
| 73 | throw SystemException( "cannot lock mutex"); | 
| 74 | } | 
| 75 | std::this_thread::sleep_for(std::chrono::milliseconds(sleepMillis)); | 
| 76 | } | 
| 77 | while (!now.isElapsed(diff)); | 
| 78 | return false; | 
| 79 | } | 
| 80 | |
| 81 | |
| 82 | |
| 83 | } // namespace Poco | 
| 84 | 
