3 * Copyright (c) 2020 Project CHIP Authors
4 * Copyright (c) 2016-2017 Nest Labs, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
21 * This file defines the abstraction of mutual exclusion locks
22 * offered by the target platform.
25 // Include module header
26 #include <system/SystemMutex.h>
28 // Include common private header
29 #include "SystemLayerPrivate.h"
31 #if !CHIP_SYSTEM_CONFIG_NO_LOCKING
33 // Include system headers
40 * Initialize the mutual exclusion lock instance.
42 * @param[in,out] aThis A zero-initialized object.
44 * @retval #CHIP_SYSTEM_NO_ERROR The mutual exclusion lock is ready to use.
45 * @retval #CHIP_SYSTEM_ERROR_NO_MEMORY Insufficient system memory to allocate the mutual exclusion lock.
46 * @retval #CHIP_SYSTEM_ERROR_UNEXPECTED_STATE An unexpected system error encountered during initialization.
49 #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING
50 DLL_EXPORT Error Mutex::Init(Mutex & aThis)
52 int lSysError = pthread_mutex_init(&aThis.mPOSIXMutex, nullptr);
58 lError = CHIP_SYSTEM_NO_ERROR;
62 lError = CHIP_SYSTEM_ERROR_NO_MEMORY;
66 lError = CHIP_SYSTEM_ERROR_UNEXPECTED_STATE;
72 #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING
74 #if CHIP_SYSTEM_CONFIG_FREERTOS_LOCKING
75 DLL_EXPORT Error Mutex::Init(Mutex & aThis)
78 if (__sync_bool_compare_and_swap(&aThis.mInitialized, 0, 1))
80 #if (configSUPPORT_STATIC_ALLOCATION == 1)
81 aThis.mFreeRTOSSemaphore = xSemaphoreCreateMutexStatic(&aThis.mFreeRTOSSemaphoreObj);
83 aThis.mFreeRTOSSemaphore = xSemaphoreCreateMutex();
85 if (aThis.mFreeRTOSSemaphore == NULL)
87 aThis.mInitialized = 0;
89 return CHIP_SYSTEM_ERROR_NO_MEMORY;
94 while (aThis.mFreeRTOSSemaphore == NULL)
98 if (aThis.mInitialized == 0)
105 return CHIP_SYSTEM_NO_ERROR;
108 DLL_EXPORT void Mutex::Lock(void)
110 xSemaphoreTake(this->mFreeRTOSSemaphore, portMAX_DELAY);
112 #endif // CHIP_SYSTEM_CONFIG_FREERTOS_LOCKING
114 } // namespace System
117 #endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING