42 lines · cpp
1//===-- Implementation of pthread_spin_trylock function -------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/pthread/pthread_spin_trylock.h"10#include "hdr/errno_macros.h"11#include "src/__support/common.h"12#include "src/__support/threads/identifier.h"13#include "src/__support/threads/spin_lock.h"14 15namespace LIBC_NAMESPACE_DECL {16 17static_assert(sizeof(pthread_spinlock_t::__lockword) == sizeof(SpinLock) &&18 alignof(decltype(pthread_spinlock_t::__lockword)) ==19 alignof(SpinLock),20 "pthread_spinlock_t::__lockword and SpinLock must be of the same "21 "size and alignment");22 23LLVM_LIBC_FUNCTION(int, pthread_spin_trylock, (pthread_spinlock_t * lock)) {24 // If an implementation detects that the value specified by the lock argument25 // to pthread_spin_lock() or pthread_spin_trylock() does not refer to an26 // initialized spin lock object, it is recommended that the function should27 // fail and report an [EINVAL] error.28 if (!lock)29 return EINVAL;30 auto spin_lock = reinterpret_cast<SpinLock *>(&lock->__lockword);31 if (!spin_lock || spin_lock->is_invalid())32 return EINVAL;33 // Try to acquire the lock without blocking.34 if (!spin_lock->try_lock())35 return EBUSY;36 // We have acquired the lock. Update the owner field.37 lock->__owner = internal::gettid();38 return 0;39}40 41} // namespace LIBC_NAMESPACE_DECL42