线程安全map

#include “controller.h”
#include
#include
#include
#include “ctrlindex.h”

template
class ThreadSaftMap
{
private:
std::map m_map;
mutable std::mutex m_mutex;
std::condition_variable m_conditionVariable;
public:
void insert(const Key &inputKey, const T &inputValue) {
std::unique_lockstd::mutex lock(m_mutex);
m_map.insert(std::pair(inputKey, inputValue));
lock.unlock();
m_conditionVariable.notify_all();
}

bool empty() const {
    std::unique_lock lock(m_mutex);
    return m_map.empty();
}

bool try_get(const Key &inputKey, T &outputValue) {
     std::unique_lock lock(m_mutex);

    typename std::map::iterator it;
    it = m_map.find(inputKey);

    if(m_map.end() == it) {
        return false;
    }

    outputValue = it->second;
    return true;
}

void wait_and_get(const Key &inputKey, T &outputValue) {
     std::unique_lock lock(m_mutex);

    typename std::map::iterator it;

    while(m_map.end() == (it = m_map.find(inputKey)))
    {
        m_conditionVariable.wait(lock);
    }

    outputValue = it->second;
}

void wait_next_insert() {
     std::unique_lock lock(m_mutex);
    m_conditionVariable.wait(lock);
}

void erase(const Key &inputKey) {
     std::unique_lock lock(m_mutex);
    m_map.erase(inputKey);
}

size_t size() const {
     std::unique_lock lock(m_mutex);
    return m_map.size();
}

};

ThreadSaftMap m_Url;

void vSetUrlController();

template
void vAddUrlController(const std::string& url);

void Server::vSetUrlController()
{
std::string strPath = “/”;
vAddUrlController(strPath);
}

template
void Server::vAddUrlController(const std::string& url)
{
// std::string strPath = “/”;

m_Url.insert(url,new CONTROLLER);

}

你可能感兴趣的:(C++)