xref: /llvm-project/libc/src/pthread/pthread_mutex_init.cpp (revision 3f30effe1bd81fa1b039218a9bfe79c3b03fafad)
1 //===-- Linux implementation of the pthread_mutex_init 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-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "pthread_mutex_init.h"
10 #include "pthread_mutexattr.h"
11 
12 #include "src/__support/common.h"
13 #include "src/__support/macros/config.h"
14 #include "src/__support/threads/mutex.h"
15 
16 #include <errno.h>
17 #include <pthread.h>
18 
19 namespace LIBC_NAMESPACE_DECL {
20 
21 static_assert(sizeof(Mutex) <= sizeof(pthread_mutex_t),
22               "The public pthread_mutex_t type cannot accommodate the internal "
23               "mutex type.");
24 
25 LLVM_LIBC_FUNCTION(int, pthread_mutex_init,
26                    (pthread_mutex_t * m,
27                     const pthread_mutexattr_t *__restrict attr)) {
28   auto mutexattr = attr == nullptr ? DEFAULT_MUTEXATTR : *attr;
29   auto err =
30       Mutex::init(reinterpret_cast<Mutex *>(m), /*is_timed=*/true,
31                   get_mutexattr_type(mutexattr) & PTHREAD_MUTEX_RECURSIVE,
32                   get_mutexattr_robust(mutexattr) & PTHREAD_MUTEX_ROBUST,
33                   get_mutexattr_pshared(mutexattr) & PTHREAD_PROCESS_SHARED);
34   return err == MutexError::NONE ? 0 : EAGAIN;
35 }
36 
37 } // namespace LIBC_NAMESPACE_DECL
38