简体   繁体   English

C++ 线程 lambda 捕获 object 可以读取但无法擦除

[英]C++ thread lambda captured object can read but cannot erase

I'm new in c++ so my problem could be very simple but I cannot solve it.我是 c++ 的新手,所以我的问题可能很简单,但我无法解决。 In my constructor I want to start detached thread which will be looping with class variable and removing old data.在我的构造函数中,我想启动分离线程,该线程将使用 class 变量循环并删除旧数据。 userCache.hpp用户缓存.hpp

struct UserCacheItem {
    long m_expires;
    oatpp::Object<User> m_user;

    UserCacheItem(const long expires, const oatpp::Object<User> &user);
};

class UserCache {
private:

    std::map<std::string, std::shared_ptr<UserCacheItem> > m_userCacheItem;

public:
    UserCache();

    void cacheUser(std::string payload, std::shared_ptr<UserCacheItem> &userCacheItem);
};

userCache.cpp用户缓存.cpp

UserCache::UserCache()
{
    std::thread thread([this]() mutable {
        while (true){
            auto curTimestamp = std::chrono::seconds(std::chrono::seconds(std::time(nullptr))).count();

            for(auto &elem : m_userCacheItem){
                if (curTimestamp > elem.second->m_expires){
                    std::cout << "Erasing element: " << elem.second->m_expires << std::endl;
                    m_userCacheItem.clear();
                }
            }

            std::cout << "Cache size: " << m_userCacheItem.size() << " Current timestamp: " << curTimestamp << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(10));
        };
    });
    thread.detach();
}

When I reach line m_userCacheItem.clear();当我到达行m_userCacheItem.clear(); I get segmentation fault.我得到分段错误。 Ofcourse if if block is false line with cout cache sizie is printed properly.当然,如果if block 是 false line with cout cache sizie 会被正确打印。 So I can read my variable but I cannot modify it:(所以我可以读取我的变量,但我不能修改它:(

Where I'm making error?我在哪里出错?

You cannot modify the map while you're iterating it迭代时不能修改 map

            for(auto &elem : m_userCacheItem){
                if (curTimestamp > elem.second->m_expires){
                    std::cout << "Erasing element: " << elem.second->m_expires << std::endl;
                    m_userCacheItem.clear();
                }
            }

If you want to erase an element, use std::map::erase:如果要擦除元素,请使用 std::map::erase:

for(auto & it = m_userCacheItem.begin(); it != m_userCacheItem.end();) {
    if(condition) {
        it = m_userCacheItem.erase(it);
    } else {
        ++it;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM