C++公共基础库(c_utils)模块
目录
- 模块概述
- 模块结构
- 模块间交互
- 状态机转换图
- 接口设计
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操作接口,支持进程间内存共享 |
设计目标
- 通用性: 提供跨子系统的通用基础能力
- 安全性: 提供线程安全的数据结构和操作接口
- 高性能: 优化内存管理和同步机制
- 易用性: 提供简洁统一的API接口
- 可扩展性: 支持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 设计思路与模式
设计思路
- 分层设计: 将功能按职责分为不同层次,降低耦合度
- 模板化设计: 使用C++模板实现通用数据结构
- RAII原则: 资源获取即初始化,确保资源安全释放
- 线程安全: 所有公共接口保证线程安全
采用的设计模式
| 设计模式 | 应用场景 | 实现类 |
|---|
| 单例模式 | 全局唯一实例管理 | 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 类
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_;
std::atomic<unsigned int> atomicFlags_;
RefPtrCallback callback_;
};
RefBase 类
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 模板类(强引用智能指针)
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 模板类(弱引用智能指针)
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 类
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 类
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();
bool WriteInt32Vector(const std::vector<int32_t> &val);
bool ReadInt32Vector(std::vector<int32_t> *val);
private:
uint8_t *data_;
size_t readCursor_;
size_t writeCursor_;
size_t dataSize_;
size_t dataCapacity_;
Allocator *allocator_;
};
2.2.3 线程管理模块
Thread 类
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 类
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 类
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_;
};
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 模板类
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 模板类
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 类
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 类
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 模板类
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 模板类
template<typename T>
class DelayedRefSingleton : public NoCopyable {
public:
static T& GetInstance();
private:
static T* instance_;
static std::mutex mutex_;
};
Singleton 模板类
template<typename T>
class Singleton : public NoCopyable {
public:
static T& GetInstance();
private:
static T instance_;
};
2.2.8 观察者模式模块
Observable 类
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 类
class Observer {
public:
virtual ~Observer() = default;
virtual void Update(const Observable* o, const ObserverArg* arg) = 0;
};
2.3 继承与多态
继承关系图
多态设计说明
| 基类 | 虚函数 | 设计目的 |
|---|
RefBase | OnFirstStrongRef(), OnLastStrongRef(), OnLastWeakRef() | 允许子类在引用计数变化时执行自定义逻辑 |
Parcelable | Marshalling() | 要求子类实现序列化逻辑 |
Thread | Run(), ReadyToWork() | 子类实现具体的线程执行逻辑 |
Observer | Update() | 子类实现具体的更新响应逻辑 |
Allocator | Alloc(), Dealloc(), Realloc() | 允许自定义内存分配策略 |
2.4 类图
智能指针模块类图
数据容器模块类图
线程管理模块类图
事件处理模块类图
2.5 模块内部依赖框图
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 异步处理与事件驱动
事件驱动模型:
3.1.4 多线程处理方式
线程池工作模式:
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 状态机树图
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 状态机树图
4.2.2 状态转换图
4.3 定时器状态机
4.3.1 状态转换图
4.4 IO事件处理状态机
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接口的类需要:
- 继承
Parcelable类 - 实现
Marshalling()虚函数 - 实现静态
Unmarshalling()函数
class MyData : public Parcelable {
public:
bool Marshalling(Parcel &parcel) const override {
return parcel.WriteInt32(value_) &&
parcel.WriteString(name_);
}
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接口协议
class MyObserver : public Observer {
public:
void Update(const Observable* o, const ObserverArg* arg) override {
if (arg != nullptr) {
}
}
};
auto observer = std::make_shared<MyObserver>();
observable->AddObserver(observer);
observable->SetChanged();
observable->NotifyObservers(&arg);
5.3 接口调用时序图
5.3.1 智能指针使用时序
5.3.2 线程池任务执行时序
5.3.3 定时器事件处理时序
5.3.4 观察者模式通知时序
附录
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) | 声明普通单例 |