一、概述
os_adapter模块是操作系统适配层。HarmonyOS的操作系统底层可以是:HarmonyOS micro kernel,Linux kernel,且 Lite OS将成为一个完整的鸿蒙微内核架构。鸿蒙系统内部各个模块内部使用的函数需要支持针对不同版本平台的适配,体现各部分解耦的模块化设计思想,针对不同的硬件设备,组合成最适合该设备的OS。当前版本的鸿蒙系统的os_adapter模块针对Lite OS内核和Linux内核实现了互斥锁和消息队列的适配。下面分别对两种内核的适配源码进行分析。
二、源码分析
- 基于LiteOS内核的os_adapter.c文件解析。
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "os_adapter.h"
#include "lwip/sockets.h"
/*创建并初始化互斥锁*/
MutexId MutexInit(void)
{
return (MutexId)osMutexNew(NULL);//创建并初始化一个新的互斥对象,并在出现错误时返回指向互斥对象标识符的指针或NULL。CMSIS-RTOS2标准
}
/*申请互斥锁*/
void MutexLock(MutexId mutex)
{
if (mutex == NULL) {
return;
}
osMutexAcquire(mutex, osWaitForever);//等待直到参数mutex指定的互斥对象变为可用。如果没有其他线程获得互斥锁,该函数会立即返回并阻塞互斥锁对象。CMSIS-RTOS2标准
}
/*释放互斥锁*/
void MutexUnlock(MutexId mutex)
{
if (mutex == NULL) {
return;
}
osMutexRelease(mutex);//释放由参数mutex指定的互斥锁。当前等待此互斥锁的其他线程将被置于READY状态。CMSIS-RTOS2标准
}
/*关闭套接字fd*/
void CloseSocket(int *fd)
{
if (fd == NULL) {
return;
}
if (*fd >= 0) {
closesocket(*fd);
*fd = -1;
}
}
/*
函数功能:向消息队列中写入一条消息
函数参数:
queueID:消息队列id
bufferAddr:要写入的消息体的首地址
bufferSize:要写入的消息体大小
函数返回值:
成功:返回0
失败:返回-1
*/
int WriteMsgQue(unsigned int queueID, const void *bufferAddr, unsigned int bufferSize)
{
if (bufferAddr == NULL) {
//健壮性检查
return -1