File size: 1,970 Bytes
83607bc
 
 
 
 
 
1a0b523
9ab4bcb
83607bc
1bff97b
83607bc
1bff97b
83607bc
 
1bff97b
83607bc
a8ba146
83607bc
 
 
 
 
 
a8ba146
83607bc
 
 
 
 
 
 
 
 
 
 
 
 
1bff97b
 
 
 
83607bc
1bff97b
 
 
 
 
83607bc
a8ba146
83607bc
 
1bff97b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83607bc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#ifndef PROXYSERVER_CONN_MAP_H
#define PROXYSERVER_CONN_MAP_H

#include <iostream>
#include <map>
#include <shared_mutex>
#include <mutex>
#include <memory>


template <typename Key, typename Value>
class SafeMap {
public:

    void add(const Key& key, std::unique_ptr<Value> &value) {
        std::unique_lock<std::shared_timed_mutex> lock(mutex_);
        map_[key] = std::move(value);
    }

    Value* get(const Key& key) const {
        std::shared_lock<std::shared_timed_mutex> lock(mutex_);
        auto it = map_.find(key);
        if (it != map_.end()) {
            return it->second.get();
        }
        return nullptr;
    }

    void remove(const Key& key) {
        std::unique_lock<std::shared_timed_mutex> lock(mutex_);
        map_.erase(key);
    }

    void clear() {
        std::unique_lock<std::shared_timed_mutex> lock(mutex_);
        map_.clear();
    }
    
    typename std::map<Key, std::unique_ptr<Value>>::iterator begin() {
        return map_.begin();
    }

    typename std::map<Key, std::unique_ptr<Value>>::iterator end() {
        return map_.end();
    }
    
protected:
    mutable std::shared_timed_mutex mutex_;
    std::map<Key, std::unique_ptr<Value>> map_;
};

template <typename Key, typename Value>
class TcpConnMap : public SafeMap<Key, Value> {
public:
    static TcpConnMap& getInstance() {
        static TcpConnMap instance; // 在首次使用时创建
        return instance;
    }

    TcpConnMap(TcpConnMap const&) = delete;
    void operator=(TcpConnMap const&) = delete;

private:
    TcpConnMap() = default;
};

template <typename Key, typename Value>
class UdpConnMap : public SafeMap<Key, Value> {
public:
    static UdpConnMap& getInstance() {
        static UdpConnMap instance; // 在首次使用时创建
        return instance;
    }

    UdpConnMap(UdpConnMap const&) = delete;
    void operator=(UdpConnMap const&) = delete;

private:
    UdpConnMap() = default;
};

#endif //PROXYSERVER_CONN_MAP_H