1# 线程安全map 2 3## 概述 4 5### 简介 6提供了一个线程安全的map实现。SafeMap在STL map基础上封装互斥锁,以确保对map的操作安全。 7 8## 涉及功能 9### class SafeMap 10#### 接口说明 11 12 13|返回类型 |名称 | 14| -------------- | -------------- | 15| | **SafeMap**() | 16| | **SafeMap**(const SafeMap& rhs) | 17| | **~SafeMap**() | 18| void | **Clear**()<br>删除map中存储的所有键值对。 | 19| void | **EnsureInsert**(const K& key, const V& value)<br>在map中插入元素。 | 20| void | **Erase**(const K& key)<br>删除map中键为key的键值对。 | 21| bool | **Find**(const K& key, V& value)<br>在map中查找元素。 | 22| bool | **FindOldAndSetNew**(const K& key, V& oldValue, const V& newValue)<br>在map中查找元素并将key对应的`oldValue`替换为`newValue`。 | 23| bool | **Insert**(const K& key, const V& value)<br>在map中插入新元素。 | 24| bool | **IsEmpty**()<br>判断map是否为空。 | 25| void | **Iterate**(const SafeMapCallBack& callback)<br>遍历map中的元素。 | 26| SafeMap& | **operator=**(const SafeMap& rhs) | 27| V& | **operator[]**(const K& key) | 28| int | **Size**()<br>获取map的size大小。 | 29 30## 使用示例 31 321. 示例代码(伪代码) 33 34```c++ 35#include <thread> 36#include <iostream> 37#include <functional> 38#include "../include/safe_map.h" 39 40using namespace OHOS; 41using namespace std; 42 43constexpr int THREAD_NUM = 5; 44thread threads[THREAD_NUM * 2]; 45SafeMap<int, string> sm; 46 47bool InsertHandler(const int& key, const string& value) 48{ 49 if (sm.Insert(key,value)) { 50 cout << "Insert key: " << key << endl; 51 return true; 52 } else { 53 return false; 54 } 55} 56 57bool FindHandler(const int& key, string& value) 58{ 59 if (sm.Find(key,value)) { 60 cout << "Find key: " << key << " with value: " << value << endl; 61 return true; 62 } else { 63 return false; 64 } 65} 66 67 68int main() 69{ 70 for (int i = 0; i < THREAD_NUM; i++) { 71 string name = "Thread" + to_string(i); 72 threads[i] = thread(&InsertHandler, i, name); 73 } 74 75 for (int i = 0; i < THREAD_NUM; i++) { 76 string out; 77 threads[i + THREAD_NUM] = thread(&FindHandler, i, ref(out)); 78 } 79 80 this_thread::sleep_for(chrono::milliseconds(300)); 81 82 for (int i = 0; i < 2 * THREAD_NUM; i++) { 83 threads[i].join(); 84 } 85 86 87 if (sm.Size() == THREAD_NUM) { 88 cout << "Insert to SafeMap success!" << endl; 89 } 90} 91``` 92 932. 测试用例编译运行方法 94 95- 测试用例代码参见base/test/unittest/common/utils_safe_map_test.cpp 96 97- 使用开发者自测试框架,使用方法参见:[开发自测试执行框架-测试用例执行](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) 98 99- 使用以下具体命令以运行`safe_map.h`对应测试用例 100 101```bash 102run -t UT -tp utils -ts UtilsSafeMapTest 103```