xref: /aosp_15_r20/external/deqp/framework/delibs/dethread/unix/deThreadLocalUnix.c (revision 35238bce31c2a825756842865a792f8cf7f89930)
1 /*-------------------------------------------------------------------------
2  * drawElements Thread Library
3  * ---------------------------
4  *
5  * Copyright 2014 The Android Open Source Project
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  *//*!
20  * \file
21  * \brief Unix implementation of thread-local storage.
22  *//*--------------------------------------------------------------------*/
23 
24 #include "deThreadLocal.h"
25 
26 #if (DE_OS == DE_OS_UNIX || DE_OS == DE_OS_OSX || DE_OS == DE_OS_ANDROID || DE_OS == DE_OS_SYMBIAN || \
27      DE_OS == DE_OS_IOS || DE_OS == DE_OS_QNX || DE_OS == DE_OS_FUCHSIA)
28 
29 #if !defined(_XOPEN_SOURCE) || (_XOPEN_SOURCE < 500)
30 #error You are using too old posix API!
31 #endif
32 
33 #include <pthread.h>
34 
35 DE_STATIC_ASSERT(sizeof(pthread_key_t) <= sizeof(deThreadLocal));
36 
37 /* \note 0 is valid pthread_key_t, but not valid for deThreadLocal */
38 
keyToThreadLocal(pthread_key_t key)39 DE_INLINE deThreadLocal keyToThreadLocal(pthread_key_t key)
40 {
41     return (deThreadLocal)(key + 1);
42 }
43 
threadLocalToKey(deThreadLocal threadLocal)44 DE_INLINE pthread_key_t threadLocalToKey(deThreadLocal threadLocal)
45 {
46     DE_ASSERT(threadLocal != 0);
47     return (pthread_key_t)(threadLocal - 1);
48 }
49 
deThreadLocal_create(void)50 deThreadLocal deThreadLocal_create(void)
51 {
52     pthread_key_t key = (pthread_key_t)0;
53     if (pthread_key_create(&key, DE_NULL) != 0)
54         return 0;
55     return keyToThreadLocal(key);
56 }
57 
deThreadLocal_destroy(deThreadLocal threadLocal)58 void deThreadLocal_destroy(deThreadLocal threadLocal)
59 {
60     int ret = 0;
61     ret     = pthread_key_delete(threadLocalToKey(threadLocal));
62     DE_ASSERT(ret == 0);
63     DE_UNREF(ret);
64 }
65 
deThreadLocal_get(deThreadLocal threadLocal)66 void *deThreadLocal_get(deThreadLocal threadLocal)
67 {
68     return pthread_getspecific(threadLocalToKey(threadLocal));
69 }
70 
deThreadLocal_set(deThreadLocal threadLocal,void * value)71 void deThreadLocal_set(deThreadLocal threadLocal, void *value)
72 {
73     int ret = 0;
74     ret     = pthread_setspecific(threadLocalToKey(threadLocal), value);
75     DE_ASSERT(ret == 0);
76     DE_UNREF(ret);
77 }
78 
79 #endif /* DE_OS */
80