1 /* 2 * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 #ifndef SHARE_GC_Z_ZLOCK_INLINE_HPP 25 #define SHARE_GC_Z_ZLOCK_INLINE_HPP 26 27 #include "gc/z/zLock.hpp" 28 #include "runtime/atomic.hpp" 29 #include "runtime/thread.hpp" 30 #include "utilities/debug.hpp" 31 32 inline ZLock::ZLock() { 33 pthread_mutex_init(&_lock, NULL); 34 } 35 36 inline ZLock::~ZLock() { 37 pthread_mutex_destroy(&_lock); 38 } 39 40 inline void ZLock::lock() { 41 pthread_mutex_lock(&_lock); 42 } 43 44 inline bool ZLock::try_lock() { 45 return pthread_mutex_trylock(&_lock) == 0; 46 } 47 48 inline void ZLock::unlock() { 49 pthread_mutex_unlock(&_lock); 50 } 51 52 inline ZReentrantLock::ZReentrantLock() : 53 _lock(), 54 _owner(NULL), 55 _count(0) {} 56 57 inline void ZReentrantLock::lock() { 58 Thread* const thread = Thread::current(); 59 Thread* const owner = Atomic::load(&_owner); 60 61 if (owner != thread) { 62 _lock.lock(); 63 Atomic::store(thread, &_owner); 64 } 65 66 _count++; 67 } 68 69 inline void ZReentrantLock::unlock() { 70 assert(is_owned(), "Invalid owner"); 71 assert(_count > 0, "Invalid count"); 72 73 _count--; 74 75 if (_count == 0) { 76 Atomic::store((Thread*)NULL, &_owner); 77 _lock.unlock(); 78 } 79 } 80 81 inline bool ZReentrantLock::is_owned() const { 82 Thread* const thread = Thread::current(); 83 Thread* const owner = Atomic::load(&_owner); 84 return owner == thread; 85 } 86 87 template <typename T> 88 inline ZLocker<T>::ZLocker(T* lock) : 89 _lock(lock) { 90 _lock->lock(); 91 } 92 93 template <typename T> 94 inline ZLocker<T>::~ZLocker() { 95 _lock->unlock(); 96 } 97 98 #endif // SHARE_GC_Z_ZLOCK_INLINE_HPP