1 Star 0 Fork 0

Tzewa Lam/DesignPatternsInCpp

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.cpp 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
Tzewa Lam 提交于 2024-07-21 19:54 +08:00 . modified 格式
#include <atomic>
#include <iostream>
#include <mutex>
#include <unordered_map>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
class ShoppingCart {
private:
ShoppingCart() = default;
public:
~ShoppingCart() = default;
ShoppingCart(ShoppingCart const &other) = delete;
ShoppingCart(ShoppingCart const &&other) = delete;
ShoppingCart &operator=(ShoppingCart const &other) = delete;
ShoppingCart &operator=(ShoppingCart const &&other) = delete;
static ShoppingCart *GetInstance() {
ShoppingCart *cart = mAtomic.load();
if (cart == nullptr) {
std::unique_lock<std::mutex> lock(mMutex);
cart = mAtomic.load();
if (cart == nullptr) {
cart = new ShoppingCart;
mAtomic.store(cart);
}
}
return cart;
}
void addItem(std::string item, int cnt) {
if (item.empty() or cnt <= 0)
return;
order.push_back(item);
items[item] += cnt;
}
void showItem() {
for (std::string const &item : order) {
cout << item << " " << items[item] << endl;
}
}
private:
std::unordered_map<std::string, int> items; // 保存购物车物品和数量
std::vector<std::string> order; // 保证购物车物品顺序
static std::mutex mMutex; // 保证线程安全
static std::atomic<ShoppingCart *> mAtomic; // 保证线程安全
};
std::atomic<ShoppingCart *> ShoppingCart::mAtomic;
std::mutex ShoppingCart::mMutex;
int main() {
int cnt;
std::string name;
while (cin >> name >> cnt) {
ShoppingCart::GetInstance()->addItem(name, cnt);
}
ShoppingCart::GetInstance()->showItem();
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/fingsinz/design-patterns-in-cpp.git
git@gitee.com:fingsinz/design-patterns-in-cpp.git
fingsinz
design-patterns-in-cpp
DesignPatternsInCpp
master

搜索帮助