Skip to content

Instantly share code, notes, and snippets.

@xueliu
Created June 4, 2020 15:11
Show Gist options
  • Save xueliu/686e240bee9d9de182321ddbcd5fbc92 to your computer and use it in GitHub Desktop.
Save xueliu/686e240bee9d9de182321ddbcd5fbc92 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
#include <mutex>
#include <unordered_map>
using namespace std;
class Stock
{
public:
Stock(const string& name)
: name_(name)
{
}
const string& key() const { return name_; }
private:
string name_;
};
// 对象池
class StockFactory
{
public:
std::shared_ptr<Stock> get(const string& key)
{
std::shared_ptr<Stock> pStock;
std::lock_guard<std::mutex> lock(mutex_);
std::weak_ptr<Stock>& wkStock = stocks_[key];
pStock = wkStock.lock();
if (!pStock)
{
pStock.reset(new Stock(key),
[this] (Stock* stock) { deleteStock(stock); });
wkStock = pStock;
}
return pStock;
}
private:
void deleteStock(Stock* stock)
{
if (stock)
{
muduo::MutexLockGuard lock(mutex_);
auto it = stocks_.find(stock->key());
assert(it != stocks_.end());
if (it->second.expired())
{
stocks_.erase(it);
}
}
delete stock;
}
mutable std::mutex mutex_;
std::unordered_map<string, std::weak_ptr<Stock> > stocks_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment