1# 线程安全栈与队列
2
3## 概述
4
5### 简介
6
7线程安全队列,是在dequeue的基础上封装std::lock_guard,以此实现线程的相关操作。根据继承SafeQueueInner抽象类,并对dequeue的pop方法的重写,可以实现SafeStack和SafeQueue的相关方法。
8
9`#include <safe_queue.h>`
10
11## 涉及功能
12
13### 接口说明
14
15### OHOS::SafeQueueInner
16
17| 返回值 | 名称                                                         |
18| ------ | ------------------------------------------------------------ |
19|        | **SafeQueueInner**()<br/>构造函数                            |
20|        | virtual **~SafeQueueInner**()<br/>析构函数                   |
21| void   | **Erase**(T& object)<br/>移除某个元素                        |
22| bool   | **Empty**()<br/>队列判空                                     |
23| void   | **Clear**()<br/>清空队列元素                                 |
24| int    | **Size**()<br/>获取队列的容量                                |
25| void   | **Push**(const T& pt)<br/>入队操作                           |
26| void   | virtual void **DoPush**(const T& pt) = 0<br/>Push底层调用DoPush,需要重写 |
27| bool   | **Pop**(T& pt)<br/>出队操作                                  |
28| bool   | virtual **DoPop**(T& pt) = 0<br/>Push底层调用DoPop,需要重写 |
29
30### OHOS::SafeQueue
31#### class SafeQueue : public SafeQueueInner
32
33| 返回值 | 名称                        |
34| ------ | ------------------------------------ |
35| void   | **DoPush**(const T& pt)<br/>入队操作 |
36| bool   | **DoPop**(T& pt)<br/>出队操作        |
37
38### OHOS::SafeStack
39#### class SafeStack : public SafeQueueInner
40
41| 返回值 | 名称                                 |
42| ------ | ------------------------------------ |
43| void   | **DoPush**(const T& pt)<br/>入栈操作 |
44| bool   | **DoPop**(T& pt)<br/>出栈操作        |
45
46## 使用示例
47
481. 示例代码
49
50```c++
51#include <thread>
52#include <iostream>
53#include <functional>
54#include "../include/safe_queue.h"
55
56using namespace OHOS;
57using namespace std;
58
59constexpr int SIZE = 4;
60
61int main() {
62    SafeQueue<int> sq;
63    SafeStack<int> st;
64
65    for (int i = 0; i < SIZE; i++) {
66        sq.Push(i);
67        st.Push(i);
68    }
69
70    for (int i = 0; i < SIZE; i++) {
71        int queOut;
72        int stackOut;
73        sq.Pop(queOut);
74        st.Pop(stackOut);
75
76        cout << "SafeQueue pop: " << queOut << endl;
77        cout << "SafeStack pop: " << stackOut <<endl;
78    }
79}
80```
81
822. 测试用例编译运行方法
83
84- 测试用例代码参见base/test/unittest/common/utils_safe_queue_test.cpp
85
86- 使用开发者自测试框架,使用方法参见:[开发自测试执行框架-测试用例执行](https://gitee.com/openharmony/testfwk_developer_test#%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B%E6%89%A7%E8%A1%8C)
87
88- 使用以下具体命令以运行`safe_queue.h`对应测试用例
89```bash
90run -t UT -tp utils -ts UtilsSafeQueueTest
91```
92
93## 常见问题
94