48 lines · cpp
1//===-- Implementation of pthread_spin_lock 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_lock.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_lock, (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->is_invalid())32 return EINVAL;33 34 pid_t self_tid = internal::gettid();35 // If an implementation detects that the value specified by the lock argument36 // to pthread_spin_lock() refers to a spin lock object for which the calling37 // thread already holds the lock, it is recommended that the function should38 // fail and report an [EDEADLK] error.39 if (lock->__owner == self_tid)40 return EDEADLK;41 42 spin_lock->lock();43 lock->__owner = self_tid;44 return 0;45}46 47} // namespace LIBC_NAMESPACE_DECL48