【OpenHarmony】commonlibrary_c_utils实现

C++公共基础库(c_utils)模块


目录

  1. 模块概述
  2. 模块结构
  3. 模块间交互
  4. 状态机转换图
  5. 接口设计

1. 模块概述

源码:https://gitee.com/openharmony/commonlibrary_c_utils/tree/master

1.1 功能与目标

主要功能

C++公共基础类库(c_utils)为OpenHarmony标准系统提供了一套常用的C++开发工具类,主要包括以下功能模块:

功能模块 描述
智能指针管理 提供sptr/wptr智能指针,实现自动内存管理和引用计数
数据序列化 提供Parcel数据容器,支持IPC/RPC场景下的数据序列化与反序列化
线程与同步 提供线程类、线程池、读写锁、信号量等多线程编程工具
安全数据容器 提供线程安全的Map、Queue、Vector等容器
文件与目录操作 提供文件读写、目录操作、文件映射等增强接口
定时器 提供定时器管理功能,支持单次和循环定时事件
事件处理 提供IO事件反应器,支持epoll事件驱动模型
设计模式 提供单例模式、观察者模式等常用设计模式实现
匿名共享内存 提供Ashmem操作接口,支持进程间内存共享
设计目标
  1. 通用性: 提供跨子系统的通用基础能力
  2. 安全性: 提供线程安全的数据结构和操作接口
  3. 高性能: 优化内存管理和同步机制
  4. 易用性: 提供简洁统一的API接口
  5. 可扩展性: 支持Rust语言绑定扩展

1.2 系统位置

在系统中的位置

c_utils作为OpenHarmony系统的核心基础模块,位于系统架构的底层,为上层各子系统提供基础能力支撑。

graph TB subgraph 应用层 APP[Applications] end subgraph 框架层 AAFWK[AAFWK子系统] AppExec[AppExecFWK子系统] DFX[DFX子系统] Other[其他子系统] end subgraph 基础服务层 subgraph c_utils[commonlibrary/c_utils] SmartPtr[智能指针] DataContainer[数据容器] ThreadMgmt[线程管理] FileOps[文件操作] Timer[定时器] EventProc[事件处理] DesignPattern[设计模式] SharedMem[共享内存] end end subgraph 内核层 Linux[Linux Kernel] LiteOS[LiteOS] Driver[驱动框架] end APP --> AAFWK APP --> AppExec APP --> DFX APP --> Other AAFWK --> c_utils AppExec --> c_utils DFX --> c_utils Other --> c_utils c_utils --> Linux c_utils --> LiteOS c_utils --> Driver
与其他模块的关系
关系类型 相关模块 说明
被依赖 IPC/RPC框架 使用Parcel进行数据序列化
被依赖 分布式数据管理 使用智能指针和线程池
被依赖 图形子系统 使用共享内存和同步机制
依赖 Linux内核 使用epoll、ashmem等内核特性
依赖 标准C++库 使用STL容器和线程库

1.3 设计思路与模式

设计思路
  1. 分层设计: 将功能按职责分为不同层次,降低耦合度
  2. 模板化设计: 使用C++模板实现通用数据结构
  3. RAII原则: 资源获取即初始化,确保资源安全释放
  4. 线程安全: 所有公共接口保证线程安全
采用的设计模式
设计模式 应用场景 实现类
单例模式 全局唯一实例管理 Singleton, DelayedSingleton, DelayedRefSingleton
观察者模式 事件通知机制 Observable, Observer
工厂模式 对象创建 Ashmem::CreateAshmem()
RAII模式 资源管理 UniqueWriteGuard, UniqueReadGuard, sptr, wptr
反应器模式 IO事件处理 IOEventReactor, IOEventHandler
生产者-消费者模式 任务队列 SafeBlockQueue, ThreadPool

2. 模块结构

2.1 源文件与头文件

目录结构
复制代码
commonlibrary/c_utils/
├── base/
│   ├── include/           # 公共头文件
│   │   ├── refbase.h      # 智能指针定义
│   │   ├── parcel.h       # 数据容器定义
│   │   ├── singleton.h    # 单例模式定义
│   │   ├── timer.h        # 定时器定义
│   │   ├── thread_pool.h  # 线程池定义
│   │   ├── thread_ex.h    # 线程类定义
│   │   ├── rwlock.h       # 读写锁定义
│   │   ├── safe_map.h     # 安全Map定义
│   │   ├── safe_queue.h   # 安全队列定义
│   │   ├── safe_block_queue.h  # 阻塞队列定义
│   │   ├── observer.h     # 观察者模式定义
│   │   ├── io_event_reactor.h  # IO事件反应器
│   │   ├── io_event_handler.h  # IO事件处理器
│   │   ├── ashmem.h       # 匿名共享内存
│   │   ├── mapped_file.h  # 文件映射
│   │   ├── file_ex.h      # 文件操作
│   │   ├── directory_ex.h # 目录操作
│   │   ├── string_ex.h    # 字符串操作
│   │   ├── datetime_ex.h  # 日期时间操作
│   │   ├── unique_fd.h    # 文件描述符管理
│   │   ├── sorted_vector.h # 有序向量
│   │   ├── semaphore_ex.h # 信号量
│   │   ├── nocopyable.h   # 禁止拷贝基类
│   │   ├── errors.h       # 错误码定义
│   │   └── ...
│   ├── src/               # 源文件
│   │   ├── refbase.cpp
│   │   ├── parcel.cpp
│   │   ├── timer.cpp
│   │   ├── thread_pool.cpp
│   │   ├── thread_ex.cpp
│   │   ├── rwlock.cpp
│   │   ├── observer.cpp
│   │   ├── io_event_reactor.cpp
│   │   ├── io_event_handler.cpp
│   │   ├── io_event_epoll.cpp
│   │   ├── ashmem.cpp
│   │   ├── mapped_file.cpp
│   │   ├── file_ex.cpp
│   │   ├── directory_ex.cpp
│   │   ├── string_ex.cpp
│   │   ├── datetime_ex.cpp
│   │   ├── semaphore_ex.cpp
│   │   └── rust/          # Rust绑定
│   │       ├── lib.rs
│   │       ├── ashmem.rs
│   │       ├── file_ex.rs
│   │       └── directory_ex.rs
│   └── test/              # 测试代码
│       ├── unittest/
│       ├── benchmarktest/
│       └── fuzztest/
└── docs/                  # 文档
    ├── en/
    └── zh-cn/
主要文件功能说明
文件 功能描述
refbase.h/cpp 实现引用计数基类和智能指针(sptr/wptr)
parcel.h/cpp 实现数据序列化容器,支持基本类型和对象的读写
singleton.h 实现三种单例模式模板类
timer.h/cpp 实现定时器管理,支持注册/注销定时事件
thread_pool.h/cpp 实现线程池,管理任务队列和工作线程
thread_ex.h/cpp 实现线程封装类,提供线程生命周期管理
rwlock.h/cpp 实现读写锁,支持写优先模式
safe_map.h 实现线程安全的Map容器
safe_block_queue.h 实现线程安全的阻塞队列
observer.h/cpp 实现观察者设计模式
io_event_reactor.h/cpp 实现IO事件反应器
ashmem.h/cpp 实现匿名共享内存操作
mapped_file.h/cpp 实现内存映射文件
file_ex.h/cpp 实现文件读写增强功能
errors.h 定义错误码格式和通用错误码

2.2 类、结构体、函数与方法

2.2.1 智能指针模块
RefCounter 类
cpp 复制代码
class RefCounter {
public:
    using RefPtrCallback = std::function<void()>;
    
    RefCounter();
    virtual ~RefCounter();
    
    // 引用计数操作
    int GetRefCount();
    void IncRefCount();
    void DecRefCount();
    
    // 强引用计数操作
    int IncStrongRefCount(const void *objectId);
    int DecStrongRefCount(const void *objectId);
    int GetStrongRefCount();
    
    // 弱引用计数操作
    int IncWeakRefCount(const void *objectId);
    int DecWeakRefCount(const void *objectId);
    int GetWeakRefCount();
    
    // 生命周期管理
    void ExtendObjectLifetime();
    bool IsLifeTimeExtended();
    
    // 尝试增加强引用
    bool AttemptIncStrongRef(const void *objectId, int &outCount);
    bool AttemptIncStrong(const void *objectId);
    
private:
    std::atomic<int> atomicStrong_;    // 强引用计数
    std::atomic<int> atomicWeak_;      // 弱引用计数
    std::atomic<int> atomicRefCount_;  // RefCounter对象引用计数
    std::atomic<unsigned int> atomicFlags_; // 生命周期标志
    RefPtrCallback callback_;          // 释放回调
};
RefBase 类
cpp 复制代码
class RefBase {
public:
    RefBase();
    RefBase(const RefBase &);
    RefBase &operator=(const RefBase &);
    RefBase(RefBase &&other) noexcept;
    RefBase &operator=(RefBase &&other) noexcept;
    virtual ~RefBase();
    
    // 强引用操作
    void IncStrongRef(const void *objectId);
    void DecStrongRef(const void *objectId);
    int GetSptrRefCount();
    
    // 弱引用操作
    WeakRefCounter *CreateWeakRef(void *cookie);
    void IncWeakRef(const void *objectId);
    void DecWeakRef(const void *objectId);
    int GetWptrRefCount();
    
    // 生命周期管理
    void ExtendObjectLifetime();
    bool AttemptAcquire(const void *objectId);
    bool AttemptIncStrongRef(const void *objectId);
    
    // 回调函数(可重写)
    virtual void OnFirstStrongRef(const void *);
    virtual void OnLastStrongRef(const void *);
    virtual void OnLastWeakRef(const void *);
    
private:
    RefCounter *refs_;
};
sptr 模板类(强引用智能指针)
cpp 复制代码
template <typename T>
class sptr {
public:
    sptr();
    ~sptr();
    sptr(T *other);
    sptr(const sptr<T> &other);
    sptr(sptr<T> &&other);
    
    // 工厂方法(推荐使用)
    template <typename... Args>
    static sptr<T> MakeSptr(Args&&... args);
    
    // 访问操作
    T *GetRefPtr() const;
    T &operator*() const;
    T *operator->() const;
    operator T*() const;
    explicit operator bool() const;
    
    // 赋值操作
    sptr<T> &operator=(T *other);
    sptr<T> &operator=(const sptr<T> &other);
    sptr<T> &operator=(sptr<T> &&other);
    
    // 比较操作
    bool operator==(const T *other) const;
    bool operator==(const sptr<T> &other) const;
    
    void clear();
    
private:
    T *refs_;
};
wptr 模板类(弱引用智能指针)
cpp 复制代码
template <typename T>
class wptr {
public:
    wptr();
    ~wptr();
    wptr(T *other);
    wptr(const wptr<T> &other);
    wptr(const sptr<T> &other);
    
    // 访问操作
    T *GetRefPtr() const;
    T &operator*() const;
    T *operator->() const;
    
    // 提升为强引用
    const sptr<T> promote() const;
    bool AttemptIncStrongRef(const void *objectId) const;
    
    // 赋值操作
    wptr<T> &operator=(T *other);
    wptr<T> &operator=(const wptr<T> &other);
    wptr<T> &operator=(const sptr<T> &other);
    
private:
    WeakRefCounter *refs_;
};
2.2.2 数据容器模块
Parcelable 类
cpp 复制代码
class Parcelable : public virtual RefBase {
public:
    Parcelable();
    explicit Parcelable(bool asRemote);
    virtual ~Parcelable() = default;
    
    // 序列化接口(必须实现)
    virtual bool Marshalling(Parcel &parcel) const = 0;
    
    // 行为标志
    enum BehaviorFlag { IPC = 0x01, RPC = 0x02, HOLD_OBJECT = 0x10 };
    void SetBehavior(BehaviorFlag b) const;
    void ClearBehavior(BehaviorFlag b) const;
    bool TestBehavior(BehaviorFlag b) const;
    
    bool asRemote_;
    mutable uint8_t behavior_;
};
Parcel 类
cpp 复制代码
class Parcel {
public:
    Parcel();
    explicit Parcel(Allocator *allocator);
    virtual ~Parcel();
    
    // 容量管理
    size_t GetDataSize() const;
    size_t GetDataCapacity() const;
    size_t GetWritableBytes() const;
    size_t GetReadableBytes() const;
    bool SetDataCapacity(size_t newCapacity);
    bool SetMaxCapacity(size_t maxCapacity);
    
    // 基本类型写入
    bool WriteBool(bool value);
    bool WriteInt8(int8_t value);
    bool WriteInt16(int16_t value);
    bool WriteInt32(int32_t value);
    bool WriteInt64(int64_t value);
    bool WriteUint8(uint8_t value);
    bool WriteUint16(uint16_t value);
    bool WriteUint32(uint32_t value);
    bool WriteUint64(uint64_t value);
    bool WriteFloat(float value);
    bool WriteDouble(double value);
    
    // 字符串写入
    bool WriteCString(const char *value);
    bool WriteString(const std::string &value);
    bool WriteString16(const std::u16string &value);
    
    // 缓冲区写入
    bool WriteBuffer(const void *data, size_t size);
    
    // 对象写入
    bool WriteParcelable(const Parcelable *object);
    bool WriteStrongParcelable(const sptr<Parcelable> &object);
    bool WriteRemoteObject(const Parcelable *object);
    
    // 基本类型读取
    bool ReadBool();
    int8_t ReadInt8();
    int16_t ReadInt16();
    int32_t ReadInt32();
    int64_t ReadInt64();
    // ... 其他类型
    
    // 字符串读取
    const char *ReadCString();
    const std::string ReadString();
    const std::u16string ReadString16();
    
    // 对象读取
    template <typename T>
    T *ReadParcelable();
    template <typename T>
    sptr<T> ReadStrongParcelable();
    
    // 游标操作
    bool RewindRead(size_t newPosition);
    bool RewindWrite(size_t offsets);
    size_t GetReadPosition();
    size_t GetWritePosition();
    
    // Vector读写
    bool WriteInt32Vector(const std::vector<int32_t> &val);
    bool ReadInt32Vector(std::vector<int32_t> *val);
    // ... 其他类型Vector
    
private:
    uint8_t *data_;
    size_t readCursor_;
    size_t writeCursor_;
    size_t dataSize_;
    size_t dataCapacity_;
    Allocator *allocator_;
};
2.2.3 线程管理模块
Thread 类
cpp 复制代码
class Thread {
public:
    Thread();
    virtual ~Thread();
    
    // 线程控制
    ThreadStatus Start(const std::string& name, 
                       int32_t priority = THREAD_PROI_NORMAL, 
                       size_t stack = 0);
    ThreadStatus NotifyExitSync();
    virtual void NotifyExitAsync();
    
    // 状态查询
    virtual bool ReadyToWork();
    bool IsExitPending() const;
    bool IsRunning() const;
    pthread_t GetThread() const;
    
protected:
    // 子类必须实现
    virtual bool Run() = 0;
    
private:
    pthread_t thread_;
    std::mutex lock_;
    std::condition_variable cvThreadExited_;
    ThreadStatus status_;
    volatile bool exitPending_;
    volatile bool running_;
};
ThreadPool 类
cpp 复制代码
class ThreadPool : public NoCopyable {
public:
    typedef std::function<void()> Task;
    
    explicit ThreadPool(const std::string &name = std::string());
    ~ThreadPool() override;
    
    // 线程池控制
    uint32_t Start(int threadsNum);
    void Stop();
    
    // 任务管理
    void AddTask(const Task& f);
    void SetMaxTaskNum(size_t maxSize);
    
    // 状态查询
    size_t GetMaxTaskNum() const;
    size_t GetCurTaskNum();
    size_t GetThreadsNum() const;
    std::string GetName() const;
    
private:
    bool Overloaded() const;
    void WorkInThread();
    Task ScheduleTask();
    
    std::string myName_;
    std::mutex mutex_;
    std::condition_variable hasTaskToDo_;
    std::condition_variable acceptNewTask_;
    std::vector<std::thread> threads_;
    std::deque<Task> tasks_;
    size_t maxTaskNum_;
    bool running_;
};
RWLock 类
cpp 复制代码
class RWLock : NoCopyable {
public:
    enum LockStatus {
        LOCK_STATUS_WRITE = -1,
        LOCK_STATUS_FREE = 0,
    };
    
    RWLock();
    explicit RWLock(bool writeFirst);
    ~RWLock() override;
    
    void LockRead();
    void UnLockRead();
    void LockWrite();
    void UnLockWrite();
    
private:
    bool writeFirst_;
    std::thread::id writeThreadID_;
    std::atomic_int lockCount_;
    std::atomic_uint writeWaitCount_;
};

// RAII封装
template <typename RWLockable>
class UniqueWriteGuard : NoCopyable {
public:
    explicit UniqueWriteGuard(RWLockable &rwLockable);
    ~UniqueWriteGuard() override;
private:
    RWLockable &rwLockable_;
};

template <typename RWLockable>
class UniqueReadGuard : NoCopyable {
public:
    explicit UniqueReadGuard(RWLockable &rwLockable);
    ~UniqueReadGuard() override;
private:
    RWLockable &rwLockable_;
};
2.2.4 安全容器模块
SafeMap 模板类
cpp 复制代码
template <typename K, typename V>
class SafeMap {
public:
    SafeMap();
    ~SafeMap();
    SafeMap(const SafeMap& rhs);
    SafeMap& operator=(const SafeMap& rhs);
    
    // 基本操作
    int Size();
    bool IsEmpty();
    void Clear();
    
    // 插入操作
    bool Insert(const K& key, const V& value);
    void EnsureInsert(const K& key, const V& value);
    
    // 查找操作
    bool Find(const K& key, V& value);
    V ReadVal(const K& key);
    bool FindOldAndSetNew(const K& key, V& oldValue, const V& newValue);
    
    // 删除操作
    void Erase(const K& key);
    
    // 遍历操作
    void Iterate(const SafeMapCallBack& callback);
    
    template<typename LambdaCallback>
    void ChangeValueByLambda(const K& key, LambdaCallback callback);
    
private:
    mutable std::mutex mutex_;
    std::map<K, V> map_;
};
SafeBlockQueue 模板类
cpp 复制代码
template <typename T>
class SafeBlockQueue {
public:
    explicit SafeBlockQueue(int capacity);
    virtual ~SafeBlockQueue();
    
    // 阻塞操作
    virtual void Push(T const& elem);
    T Pop();
    
    // 非阻塞操作
    virtual bool PushNoWait(T const& elem);
    bool PopNotWait(T& outtask);
    
    // 状态查询
    unsigned int Size();
    bool IsEmpty();
    bool IsFull();
    
protected:
    unsigned long maxSize_;
    std::mutex mutexLock_;
    std::condition_variable cvNotEmpty_;
    std::condition_variable cvNotFull_;
    std::queue<T> queueT_;
};

// 带任务跟踪的阻塞队列
template <typename T>
class SafeBlockQueueTracking : public SafeBlockQueue<T> {
public:
    explicit SafeBlockQueueTracking(int capacity);
    virtual ~SafeBlockQueueTracking();
    
    virtual void Push(T const& elem);
    virtual bool PushNoWait(T const& elem);
    
    bool OneTaskDone();
    void Join();
    int GetUnfinishTaskNum();
    
protected:
    std::atomic<int> unfinishedTaskCount_;
    std::condition_variable cvAllTasksDone_;
};
2.2.5 定时器模块
Timer 类
cpp 复制代码
class Timer {
public:
    using TimerCallback = std::function<void()>;
    using TimerCallbackPtr = std::shared_ptr<TimerCallback>;
    
    explicit Timer(const std::string& name, int timeoutMs = 1000);
    virtual ~Timer();
    
    // 定时器控制
    virtual uint32_t Setup();
    virtual void Shutdown(bool useJoin = true);
    
    // 事件管理
    uint32_t Register(const TimerCallback& callback, 
                      uint32_t interval, 
                      bool once = false);
    void Unregister(uint32_t timerId);
    
private:
    struct TimerEntry {
        uint32_t timerId;
        uint32_t interval;
        TimerCallback callback;
        bool once;
        int timerFd;
    };
    
    void MainLoop();
    void OnTimer(int timerFd);
    
    std::string name_;
    int timeoutMs_;
    std::thread thread_;
    EventReactor *reactor_;
    std::map<uint32_t, TimerEntryList> intervalToTimers_;
    std::map<uint32_t, TimerEntryPtr> timerToEntries_;
    std::mutex mutex_;
};
2.2.6 事件处理模块
IOEventReactor 类
cpp 复制代码
class IOEventReactor {
public:
    static constexpr uint8_t FLAG_CHANGED = 0x01;
    static constexpr size_t INIT_FD_NUMS = 8;
    
    IOEventReactor();
    virtual ~IOEventReactor();
    
    // 生命周期管理
    ErrCode SetUp();
    ErrCode CleanUp();
    ErrCode Clean(int fd);
    
    // 事件处理器管理
    ErrCode AddHandler(IOEventHandler* target);
    ErrCode RemoveHandler(IOEventHandler* target);
    ErrCode UpdateHandler(IOEventHandler* target);
    ErrCode FindHandler(IOEventHandler* target);
    
    // 事件循环
    void Run(int timeout);
    void Terminate();
    
    // 启用/禁用处理
    void EnableHandling();
    void DisableHandling();
    
private:
    struct FdEvents {
        std::shared_ptr<IOEventHandler> head;
        EventId events;
        uint8_t flags;
    };
    
    std::mutex mutex_;
    std::atomic<bool> loopReady_;
    std::atomic<bool> enabled_;
    std::vector<struct FdEvents> ioHandlers_;
    std::unique_ptr<IOEventEpoll> backend_;
};
2.2.7 单例模式模块
DelayedSingleton 模板类
cpp 复制代码
template<typename T>
class DelayedSingleton : public NoCopyable {
public:
    // 获取单例实例(线程安全,懒加载)
    static std::shared_ptr<T> GetInstance();
    
    // 销毁单例实例
    static void DestroyInstance();
    
private:
    static std::shared_ptr<T> instance_;
    static std::mutex mutex_;
};
DelayedRefSingleton 模板类
cpp 复制代码
template<typename T>
class DelayedRefSingleton : public NoCopyable {
public:
    // 获取单例引用(线程安全,懒加载)
    static T& GetInstance();
    
private:
    static T* instance_;
    static std::mutex mutex_;
};
Singleton 模板类
cpp 复制代码
template<typename T>
class Singleton : public NoCopyable {
public:
    // 获取单例引用(饿汉式,程序启动时初始化)
    static T& GetInstance();
    
private:
    static T instance_;
};
2.2.8 观察者模式模块
Observable 类
cpp 复制代码
class Observable {
public:
    virtual ~Observable() = default;
    
    // 观察者管理
    void AddObserver(const std::shared_ptr<Observer>& o);
    void RemoveObserver(const std::shared_ptr<Observer>& o);
    void RemoveAllObservers();
    
    // 通知观察者
    void NotifyObservers();
    void NotifyObservers(const ObserverArg* arg);
    
    // 状态查询
    int GetObserversCount();
    
protected:
    bool HasChanged();
    void SetChanged();
    void ClearChanged();
    
    std::set<std::shared_ptr<Observer>> obs;
    std::mutex mutex_;
    
private:
    bool changed_ = false;
};
Observer 类
cpp 复制代码
class Observer {
public:
    virtual ~Observer() = default;
    
    // 更新接口(由Observable调用)
    virtual void Update(const Observable* o, const ObserverArg* arg) = 0;
};

2.3 继承与多态

继承关系图

<<abstract>> NoCopyable #NoCopyable() #~NoCopyable() RefBase -RefCounter* refs_ +IncStrongRef() +DecStrongRef() +IncWeakRef() +DecWeakRef() +OnFirstStrongRef() +OnLastStrongRef() +OnLastWeakRef() Parcelable +bool asRemote_ +Marshalling() : bool Ashmem -int memoryFd_ -int32_t memorySize_ +CreateAshmem() : sptr<Ashmem> +MapAshmem() +WriteToAshmem() +ReadFromAshmem() RWLock -bool writeFirst_ -atomic_int lockCount_ +LockRead() +UnLockRead() +LockWrite() +UnLockWrite() ThreadPool -vector<thread> threads_ -deque<Task> tasks_ +Start() +Stop() +AddTask() SafeBlockQueue<T> #unsigned long maxSize_ #queue<T> queueT_ +Push() +Pop() SafeBlockQueueTracking<T> -atomic<int> unfinishedTaskCount_ +OneTaskDone() +Join()

多态设计说明
基类 虚函数 设计目的
RefBase OnFirstStrongRef(), OnLastStrongRef(), OnLastWeakRef() 允许子类在引用计数变化时执行自定义逻辑
Parcelable Marshalling() 要求子类实现序列化逻辑
Thread Run(), ReadyToWork() 子类实现具体的线程执行逻辑
Observer Update() 子类实现具体的更新响应逻辑
Allocator Alloc(), Dealloc(), Realloc() 允许自定义内存分配策略

2.4 类图

智能指针模块类图

持有 创建 继承 管理 持有 相互转换 RefCounter -atomic<int> atomicStrong_ -atomic<int> atomicWeak_ -atomic<int> atomicRefCount_ -RefPtrCallback callback_ +IncStrongRefCount() : int +DecStrongRefCount() : int +IncWeakRefCount() : int +DecWeakRefCount() : int +GetStrongRefCount() : int +GetWeakRefCount() : int WeakRefCounter -atomic<int> atomicWeak_ -RefCounter* refCounter_ -void* cookie_ +GetRefPtr() +IncWeakRefCount() +DecWeakRefCount() +AttemptIncStrongRef() : bool RefBase -RefCounter* refs_ +IncStrongRef() +DecStrongRef() +CreateWeakRef() +ExtendObjectLifetime() +OnFirstStrongRef() +OnLastStrongRef() sptr<T> -T* refs_ +MakeSptr() : sptr<T> +GetRefPtr() +clear() +operator*() +operator->() wptr<T> -WeakRefCounter* refs_ +GetRefPtr() +promote() : sptr<T> +AttemptIncStrongRef() : bool Parcelable +bool asRemote_ +uint8_t behavior_ +Marshalling() : bool +SetBehavior() +TestBehavior() : bool

数据容器模块类图

实现 使用 读写 <<interface>> Allocator +Alloc() +Dealloc() +Realloc() DefaultAllocator +Alloc() +Dealloc() +Realloc() Parcel -uint8_t* data_ -size_t readCursor_ -size_t writeCursor_ -size_t dataCapacity_ -Allocator* allocator_ +WriteBool() : bool +WriteInt32() : bool +WriteString() : bool +WriteParcelable() : bool +ReadBool() : bool +ReadInt32() : int32_t +ReadString() : string +ReadParcelable~T~() Parcelable +bool asRemote_ +Marshalling() : bool

线程管理模块类图

使用 使用 <<abstract>> Thread -pthread_t thread_ -mutex lock_ -bool exitPending_ -bool running_ +Start() : ThreadStatus +NotifyExitSync() : ThreadStatus +NotifyExitAsync() +IsRunning() : bool #Run() : bool ThreadPool -string myName_ -vector<thread> threads_ -deque<Task> tasks_ -size_t maxTaskNum_ -bool running_ +Start() : uint32_t +Stop() +AddTask() +GetCurTaskNum() : size_t RWLock -bool writeFirst_ -atomic_int lockCount_ -atomic_uint writeWaitCount_ +LockRead() +UnLockRead() +LockWrite() +UnLockWrite() UniqueWriteGuard<RWLockable> -RWLockable& rwLockable_ +UniqueWriteGuard() +~UniqueWriteGuard() UniqueReadGuard<RWLockable> -RWLockable& rwLockable_ +UniqueReadGuard() +~UniqueReadGuard()

事件处理模块类图

管理 使用 使用 IOEventReactor -vector<FdEvents> ioHandlers_ -unique_ptr<IOEventEpoll> backend_ -atomic<bool> loopReady_ +SetUp() : ErrCode +CleanUp() : ErrCode +AddHandler() : ErrCode +RemoveHandler() : ErrCode +Run() +Terminate() IOEventHandler -int fd_ -EventId events_ -EventCallback callback_ +Start() : ErrCode +Stop() : ErrCode +Update() : ErrCode +GetFd() : int IOEventEpoll -int epollFd_ +Add() : ErrCode +Modify() : ErrCode +Remove() : ErrCode +Polling() : int Timer -string name_ -int timeoutMs_ -thread thread_ -EventReactor* reactor_ +Setup() : uint32_t +Shutdown() +Register() : uint32_t +Unregister()

2.5 模块内部依赖框图

文件模块 事件模块 容器模块 线程模块 同步模块 核心模块 基础模块 file_ex.h
文件操作 directory_ex.h
目录操作 mapped_file.h
文件映射 ashmem.h
共享内存 io_event_common.h
事件通用 io_event_handler.h
事件处理器 io_event_reactor.h
事件反应器 timer.h
定时器 safe_map.h
安全Map safe_queue.h
安全队列 safe_block_queue.h
阻塞队列 thread_ex.h
线程类 thread_pool.h
线程池 rwlock.h
读写锁 semaphore_ex.h
信号量 singleton.h
单例模式 refbase.h
智能指针 parcel.h
数据容器 flat_obj.h
平面对象 nocopyable.h
基础宏定义 errors.h
错误码


3. 模块间交互

3.1 交互描述

3.1.1 与IPC/RPC框架的交互

c_utils通过Parcel类为IPC/RPC框架提供数据序列化能力:

  • 数据序列化 : 使用Parcel::WriteXxx()方法将数据写入Parcel
  • 数据反序列化 : 使用Parcel::ReadXxx()方法从Parcel读取数据
  • 对象传输 : 实现Parcelable接口的对象可以通过Parcel进行跨进程传输
  • 远程对象 : 通过WriteRemoteObject()/ReadObject()支持远程对象引用
3.1.2 与内核的交互
交互方式 说明
epoll IOEventReactor使用epoll实现IO事件多路复用
timerfd Timer使用timerfd实现定时器功能
ashmem Ashmem类通过/dev/ashmem设备文件操作匿名共享内存
mmap MappedFile使用mmap实现文件内存映射
pthread Thread类封装pthread接口
3.1.3 异步处理与事件驱动

事件驱动模型:
回调 系统层 反应器层 用户层 注册 委托 事件发生 触发 Callback执行 IOEventEpoll
epoll IOEventReactor IOEventHandler

3.1.4 多线程处理方式

线程池工作模式:
ThreadPool 调用方 工作线程组 AddTask 取任务 取任务 取任务 任务队列 Thread 1 Thread 2 Thread 3 调用方

3.2 外部依赖框图

graph TB subgraph c_utils[c_utils 公共基础库] SmartPtr[智能指针] Parcel[数据容器] Thread[线程管理] Timer[定时器] Event[事件处理] SafeContainer[安全容器] end subgraph 依赖库 subgraph STL[C++标准库] atomic["<atomic>"] thread["<thread>"] mutex["<mutex>"] cv["<condition_variable>"] functional["<functional>"] memory["<memory>"] containers["<map> <vector> <queue>"] end subgraph Kernel[Linux内核] epoll[epoll] timerfd[timerfd] ashmem[ashmem] mmap[mmap] pthread[pthread] end subgraph Third[第三方库] RustFFI[Rust FFI
可选] end end subgraph 被依赖 IPC[IPC/RPC框架] DDS[分布式数据管理] Graphics[图形子系统] end c_utils --> STL c_utils --> Kernel c_utils -.-> Third IPC -->|Parcel/RefBase| c_utils DDS -->|sptr/ThreadPool| c_utils Graphics -->|Ashmem/RWLock| c_utils

4. 状态机转换图

4.1 智能指针状态机

4.1.1 状态机树图

RefBase对象生命周期 未引用状态
strongCnt=0
weakCnt=0 强引用状态
strongCnt>0
weakCnt>=0 扩展生命周期状态
strongCnt=0
weakCnt>0
extended=true

4.1.2 状态切换规则
当前状态 事件/条件 目标状态 动作
未引用 IncStrongRef() 强引用 调用OnFirstStrongRef()
强引用 DecStrongRef() 且 strongCnt=0 未引用/销毁 调用OnLastStrongRef(),如未扩展则销毁
强引用 ExtendObjectLifetime() 扩展生命周期 设置扩展标志
扩展生命周期 DecWeakRef() 且 weakCnt=0 销毁 调用OnLastWeakRef()并销毁
4.1.3 状态转换图
stateDiagram-v2 [*] --> Initial: 对象创建 Initial --> StrongRef: IncStrongRef()
OnFirstStrongRef() StrongRef --> StrongRef: DecStrong(cnt>0) StrongRef --> Destroyed: DecStrong(cnt=0)
!extended
OnLastStrongRef() StrongRef --> Extended: ExtendLifetime() Extended --> Destroyed: DecWeak(cnt=0)
OnLastWeakRef() Destroyed --> [*] state Initial { [*] --> Unreferenced note right of Unreferenced: strongCnt=0
weakCnt=0 } state StrongRef { [*] --> Referenced note right of Referenced: strongCnt>0 } state Extended { [*] --> ExtendedLife note right of ExtendedLife: strongCnt=0
weakCnt>0
extended=true }

4.2 线程状态机

4.2.1 状态机树图

Thread生命周期 初始状态
running=false
exitPending=false 运行状态
running=true
exitPending=false 退出等待状态
running=true
exitPending=true 终止状态
running=false

4.2.2 状态转换图

Start() Run()返回true NotifyExit() Run()返回false Run()返回true Run()返回false Created Running ExitPending Terminated 线程未启动 线程执行中 等待退出 线程已终止

4.3 定时器状态机

4.3.1 状态转换图

Setup() Register() Timeout(once=false) Register()新事件 Unregister()所有事件 Shutdown() Shutdown() Created Ready Active Shutdown 定时器已创建 就绪,无活动事件 有活动的定时事件 定时器已关闭

4.4 IO事件处理状态机

SetUp() AddHandler() Run() 事件处理完成 Terminate() RemoveHandler()所有 Terminate() CleanUp() Created Ready Active Polling Stopped Destroyed 反应器已创建 已初始化 有活动Handler 轮询事件中 已停止 已销毁


5. 接口设计

5.1 公共接口

5.1.1 智能指针接口
sptr<T>::MakeSptr()
项目 说明
功能 创建新对象并返回管理该对象的sptr智能指针(推荐方式)
原型 template <typename... Args> static sptr<T> MakeSptr(Args&&... args)
参数 args - 传递给T类型构造函数的参数
返回值 管理新创建对象的sptr智能指针
异常 内存分配失败时抛出std::bad_alloc
线程安全
wptr<T>::promote()
项目 说明
功能 将弱引用提升为强引用
原型 const sptr<T> promote() const
参数
返回值 成功返回有效sptr,失败返回空sptr
异常
线程安全
5.1.2 数据容器接口
Parcel::WriteInt32()
项目 说明
功能 向Parcel写入32位整数
原型 bool WriteInt32(int32_t value)
参数 value - 要写入的整数值
返回值 成功返回true,失败返回false
异常
线程安全 否(需外部同步)
Parcel::ReadInt32()
项目 说明
功能 从Parcel读取32位整数
原型 int32_t ReadInt32()
参数
返回值 读取的整数值
异常
线程安全 否(需外部同步)
Parcel::WriteParcelable()
项目 说明
功能 向Parcel写入Parcelable对象
原型 bool WriteParcelable(const Parcelable *object)
参数 object - 要写入的Parcelable对象指针
返回值 成功返回true,失败返回false
异常
线程安全 否(需外部同步)
5.1.3 线程管理接口
ThreadPool::Start()
项目 说明
功能 启动指定数量的工作线程
原型 uint32_t Start(int threadsNum)
参数 threadsNum - 要启动的线程数量
返回值 成功返回ERR_OK,失败返回错误码
异常
线程安全
ThreadPool::AddTask()
项目 说明
功能 向任务队列添加任务
原型 void AddTask(const Task& f)
参数 f - 任务函数对象
返回值
异常
线程安全
RWLock::LockRead() / UnLockRead()
项目 说明
功能 获取/释放读锁
原型 void LockRead() / void UnLockRead()
参数
返回值
异常
线程安全
RWLock::LockWrite() / UnLockWrite()
项目 说明
功能 获取/释放写锁
原型 void LockWrite() / void UnLockWrite()
参数
返回值
异常
线程安全
5.1.4 定时器接口
Timer::Setup()
项目 说明
功能 初始化定时器
原型 virtual uint32_t Setup()
参数
返回值 成功返回ERR_OK,失败返回错误码
异常
线程安全 否(需在单线程中调用)
Timer::Register()
项目 说明
功能 注册定时事件
原型 uint32_t Register(const TimerCallback& callback, uint32_t interval, bool once = false)
参数 callback - 回调函数; interval - 间隔(ms); once - 是否单次
返回值 定时器ID
异常
线程安全
Timer::Unregister()
项目 说明
功能 注销定时事件
原型 void Unregister(uint32_t timerId)
参数 timerId - 要注销的定时器ID
返回值
异常
线程安全
5.1.5 单例模式接口
DelayedSingleton<T>::GetInstance()
项目 说明
功能 获取单例实例(懒加载,线程安全)
原型 static std::shared_ptr<T> GetInstance()
参数
返回值 单例对象的shared_ptr
异常 内存分配失败时返回nullptr
线程安全 是(双重检查锁定)
DelayedSingleton<T>::DestroyInstance()
项目 说明
功能 销毁单例实例
原型 static void DestroyInstance()
参数
返回值
异常
线程安全

5.2 数据交换接口

5.2.1 Parcelable接口协议

实现Parcelable接口的类需要:

  1. 继承Parcelable
  2. 实现Marshalling()虚函数
  3. 实现静态Unmarshalling()函数
cpp 复制代码
class MyData : public Parcelable {
public:
    // 序列化:将对象数据写入Parcel
    bool Marshalling(Parcel &parcel) const override {
        return parcel.WriteInt32(value_) && 
               parcel.WriteString(name_);
    }
    
    // 反序列化:从Parcel读取数据创建对象
    static MyData* Unmarshalling(Parcel &parcel) {
        auto data = new MyData();
        data->value_ = parcel.ReadInt32();
        data->name_ = parcel.ReadString();
        return data;
    }
    
private:
    int32_t value_;
    std::string name_;
};
5.2.2 Observer接口协议
cpp 复制代码
class MyObserver : public Observer {
public:
    // 当被观察对象状态改变时调用
    void Update(const Observable* o, const ObserverArg* arg) override {
        // 处理更新通知
        if (arg != nullptr) {
            // 使用arg中的数据
        }
    }
};

// 使用示例
auto observer = std::make_shared<MyObserver>();
observable->AddObserver(observer);
observable->SetChanged();
observable->NotifyObservers(&arg);

5.3 接口调用时序图

5.3.1 智能指针使用时序

调用方 sptr RefBase RefCounter MakeSptr<T>() new T() new RefCounter() 返回 返回对象 IncStrongRef() IncStrongRefCount() 返回计数 OnFirstStrongRef() 返回sptr 使用对象... ~sptr() DecStrongRef() DecStrongRefCount() 返回计数(0) OnLastStrongRef() delete this 调用方 sptr RefBase RefCounter

5.3.2 线程池任务执行时序

调用方 ThreadPool 任务队列 工作线程 Start(n) 创建n个工作线程 线程就绪 AddTask(task) push(task) notify_one() pop() 返回task 执行task() Stop() running_ = false notify_all() join() 线程退出 调用方 ThreadPool 任务队列 工作线程

5.3.3 定时器事件处理时序

调用方 Timer EventReactor timerfd Setup() SetUp() 启动事件循环线程 返回 Register(cb, 1000) timerfd_create() 返回fd timerfd_settime() AddHandler() 返回timerId 等待1000ms... epoll_wait() 超时事件 OnTimer() callback() Shutdown() CleanUp() 返回 调用方 Timer EventReactor timerfd

5.3.4 观察者模式通知时序

调用方 Observable Observer1 Observer2 AddObserver(o1) obs.insert(o1) 返回 AddObserver(o2) obs.insert(o2) 返回 SetChanged() changed_ = true 返回 NotifyObservers(arg) Update(this, arg) 处理完成 Update(this, arg) 处理完成 changed_ = false 返回 调用方 Observable Observer1 Observer2


附录

A. 错误码定义

错误码 名称 说明
0 ERR_OK 操作成功
BASE_ERR_OFFSET + ENOMEM ERR_NO_MEMORY 内存不足
BASE_ERR_OFFSET + ENOSYS ERR_INVALID_OPERATION 无效操作
BASE_ERR_OFFSET + EINVAL ERR_INVALID_VALUE 无效参数
BASE_ERR_OFFSET + ENOENT ERR_NAME_NOT_FOUND 名称未找到
BASE_ERR_OFFSET + EPERM ERR_PERMISSION_DENIED 权限拒绝
BASE_ERR_OFFSET + ENODEV ERR_NO_INIT 未初始化
BASE_ERR_OFFSET + EEXIST ERR_ALREADY_EXISTS 已存在
BASE_ERR_OFFSET + EPIPE ERR_DEAD_OBJECT 对象已销毁
BASE_ERR_OFFSET + EOVERFLOW ERR_OVERFLOW 溢出
BASE_ERR_OFFSET + ETIMEDOUT ERR_TIMED_OUT 超时

B. 使用宏定义

说明
DISALLOW_COPY_AND_MOVE(className) 禁止类的拷贝和移动
DISALLOW_COPY(className) 禁止类的拷贝
DISALLOW_MOVE(className) 禁止类的移动
DECLARE_DELAYED_SINGLETON(MyClass) 声明延迟单例
DECLARE_DELAYED_REF_SINGLETON(MyClass) 声明延迟引用单例
DECLARE_SINGLETON(MyClass) 声明普通单例
相关推荐
古城小栈14 小时前
Rust语言:优势解析与擅长领域深度探索
开发语言·后端·rust
superman超哥14 小时前
Rust Cargo.toml 配置文件详解:项目管理的核心枢纽
开发语言·后端·rust·rust cargo.toml·cargo.toml配置文件
玄同76514 小时前
面向对象编程 vs 其他编程范式:LLM 开发该选哪种?
大数据·开发语言·前端·人工智能·python·自然语言处理·知识图谱
白书宇14 小时前
【STM32实战】从零开始写Linux 0.12内核 第1个实验安装IAR 8.5
linux·c语言·驱动开发·stm32·单片机·嵌入式硬件
froginwe1114 小时前
SQLite Indexed By
开发语言
虾说羊14 小时前
JVM 高频面试题全解析
java·开发语言·jvm
lengjingzju14 小时前
一网打尽Linux IPC(四):POSIX IPC
linux·服务器·c语言
毕设源码-赖学姐15 小时前
【开题答辩全过程】以 基于PHP的国学诗词网站与推荐系统的设计与实现为例,包含答辩的问题和答案
开发语言·php
盼哥PyAI实验室15 小时前
[特殊字符]️ 实战爬虫:Python 抓取【采购公告】接口数据(含踩坑解析)
开发语言·爬虫·python