1 //===-- Implementation of pthread_spin_trylock function -------------------===//
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-exception
7 //===----------------------------------------------------------------------===//
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"
15 namespace LIBC_NAMESPACE_DECL
{
17 static_assert(sizeof(pthread_spinlock_t::__lockword
) == sizeof(SpinLock
) &&
18 alignof(decltype(pthread_spinlock_t::__lockword
)) ==
20 "pthread_spinlock_t::__lockword and SpinLock must be of the same "
21 "size and alignment");
23 LLVM_LIBC_FUNCTION(int, pthread_spin_trylock
, (pthread_spinlock_t
* lock
)) {
24 // If an implementation detects that the value specified by the lock argument
25 // to pthread_spin_lock() or pthread_spin_trylock() does not refer to an
26 // initialized spin lock object, it is recommended that the function should
27 // fail and report an [EINVAL] error.
30 auto spin_lock
= reinterpret_cast<SpinLock
*>(&lock
->__lockword
);
31 if (!spin_lock
|| spin_lock
->is_invalid())
33 // Try to acquire the lock without blocking.
34 if (!spin_lock
->try_lock())
36 // We have acquired the lock. Update the owner field.
37 lock
->__owner
= internal::gettid();
41 } // namespace LIBC_NAMESPACE_DECL