Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

你好 协程里是否可以使用std的读写锁? #372

Open
pya789 opened this issue Sep 9, 2024 · 0 comments
Open

你好 协程里是否可以使用std的读写锁? #372

pya789 opened this issue Sep 9, 2024 · 0 comments

Comments

@pya789
Copy link

pya789 commented Sep 9, 2024

我有一个简单的缓存类 他给别的进程使用通过co库建立的套接字通信 每个读/写都是一个协程 读写操作都在一个实例里进行是否可以像下面一样使用std的读写锁进程操作?

void Cache::set(const std::string &key, const std::string &value, std::chrono::seconds expirationTime)
    {
        std::unique_lock<std::shared_mutex> lock(mutex_);
        if (expirationTime.count() == 0)
        {
            expirationTime = defaultExpirationTime_;
        }
        CacheItem item{value, std::chrono::steady_clock::now(), expirationTime};
        cache_[key] = item;
    }
    std::string Cache::get(const std::string &key)
    {
        std::shared_lock<std::shared_mutex> lock(mutex_);
        auto it = cache_.find(key);
        if (it == cache_.end())
        {
            return "";
        }
        const CacheItem &item = it->second;
        auto now = std::chrono::steady_clock::now();
        if (item.expirationTime.count() > 0 && (now - item.timestamp > item.expirationTime))
        {
            cache_.erase(it);
            return "";
        }
        return item.data;
    }
    ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant