一. 带定时器和锁的LRU缓存
#include <iostream>
#include <unordered_map>
#include <chrono>
#include <mutex>
#include <thread>
using namespace std;
class LRUCache {
public:
typedef struct Node {
int key;
int data;
Node* pre;
Node* next;
chrono::steady_clock::time_point timestamp;
Node() : key(0), data(0), pre(nullptr), next(nullptr), timestamp(chrono::steady_clock::now()) {}
Node(int key, int val) : key(key), data(val), pre(nullptr), next(nullptr), timestamp(chrono::steady_clock::now()) {}
}Node, *pNode;
int capacity;
unordered_map<int, pNode> m;
Node* listpre = new Node();
Node* listtail = new Node();
mutex mtx;
const chrono::seconds ttl = chrono::seconds(5);
LRUCache(int capacity) {
this->capacity = capacity;
listpre->next = listtail;
listtail->pre = listpre;
thread(&LRUCache::cleanUpExpired, this).detach();
}
void remove(Node* cur) {
Node* pre = cur->pre;
Node* next = cur->next;
pre->next = next;
next->pre = pre;
}
void update(Node* cur) {
remove(cur);
insert(cur);
cur->timestamp = chrono::steady_clock::now();
}
void insert(Node* cur) {
listtail->pre->next = cur;
cur->pre = listtail->pre;
cur->next = listtail;
listtail->pre = cur;
}
void release() {
Node* cur = listpre->next;
m.erase(cur->key);
remove(cur);
delete cur;
}
void cleanUpExpired() {
while (true) {
this_thread::sleep_for(chrono::seconds(1));
lock_guard<mutex> lock(mtx);
auto now = chrono::steady_clock::now();
Node* cur = listpre->next;
while (cur != listtail) {
if (chrono::duration_cast<chrono::seconds>(now - cur->timestamp) >= ttl) {
Node* next = cur->next;
m.erase(cur->key);
remove(cur);
delete cur;
cur = next;
} else {
cur = cur->next;
}
}
}
}
int get(int key) {
lock_guard<mutex> lock(mtx);
if (m.count(key) == 0) return -1;
Node* cur = m[key];
if (chrono::duration_cast<chrono::seconds>(chrono::steady_clock::now() - cur->timestamp) >= ttl) {
m.erase(key);
remove(cur);
delete cur;
return -1;
}
update(cur);
return cur->data;
}
void put(int key, int value) {
lock_guard<mutex> lock(mtx);
if (m.count(key)) {
Node* cur = m[key];
cur->data = value;
update(cur);
return;
}
if (m.size() == capacity) release();
Node* cur = new Node(key, value);
m[key] = cur;
insert(cur);
}
};
二. 循环打印123
package main
import (
"fmt"
"sync"
)
func main() {
ch1 := make(chan bool)
ch2 := make(chan bool)
ch3 := make(chan bool)
bufferSize := 5
ch := make(chan int, bufferSize)
ch <- 1
var wg sync.WaitGroup
var mutex sync.Mutex
mutex.Lock()
defer mutex.Unlock()
wg.Add(3)
go func() {
defer wg.Done()
for i := 0; i < 3; i++ {
<-ch1
fmt.Println(1)
ch2 <- true
}
}()
go func() {
defer wg.Done()
for i := 0; i < 3; i++ {
<-ch2
fmt.Println(2)
ch3 <- true
}
}()
go func() {
defer wg.Done()
for i := 0; i < 3; i++ {
<-ch3
fmt.Println(3)
if i < 2 {
ch1 <- true
}
}
}()
ch1 <- true
wg.Wait()
}
三. 单例模式
#include <iostream>
#include <mutex>
class LazySingleton {
private:
static LazySingleton* instance;
static std::mutex mtx;
LazySingleton() {
std::cout << "LazySingleton Constructor Called" << std::endl;
}
public:
LazySingleton(const LazySingleton&) = delete;
LazySingleton& operator=(const LazySingleton&) = delete;
static LazySingleton* getInstance() {
if (instance == nullptr) {
std::lock_guard<std::mutex> lock(mtx);
if (instance == nullptr) {
instance = new LazySingleton();
}
}
return instance;
}
};
class EagerSingleton {
private:
static EagerSingleton instance;
EagerSingleton() {
std::cout << "EagerSingleton Constructor Called" << std::endl;
}
public:
EagerSingleton(const EagerSingleton&) = delete;
EagerSingleton& operator=(const EagerSingleton&) = delete;
static EagerSingleton& getInstance() {
return instance;
}
};
class LazySingleton {
private:
LazySingleton() {
std::cout << "LazySingleton Constructor Called" << std::endl;
}
public:
LazySingleton(const LazySingleton&) = delete;
LazySingleton& operator=(const LazySingleton&) = delete;
static LazySingleton& getInstance() {
static LazySingleton instance;
return instance;
}
};
四. 工厂模式
#include <iostream>
#include <memory>
class Product {
public:
virtual void show() const = 0;
virtual ~Product() = default;
};
class ProductA : public Product {
public:
void show() const override {
std::cout << "This is Product A." << std::endl;
}
};
class ProductB : public Product {
public:
void show() const override {
std::cout << "This is Product B." << std::endl;
}
};
class Factory {
public:
std::unique_ptr<Product> createProduct(const std::string& type) {
if (type == "A") {
return std::make_unique<ProductA>();
} else if (type == "B") {
return std::make_unique<ProductB>();
} else {
return nullptr;
}
}
};
int main() {
Factory factory;
std::unique_ptr<Product> productA = factory.createProduct("A");
if (productA) productA->show();
std::unique_ptr<Product> productB = factory.createProduct("B");
if (productB) productB->show();
return 0;
}
五. 观察者模式
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
class Observer {
public:
virtual void update(const std::string& message) = 0;
virtual ~Observer() = default;
};
class ConcreteObserver1 : public Observer {
public:
void update(const std::string& message) override {
std::cout << "ConcreteObserver1 received: " << message << std::endl;
}
};
class ConcreteObserver2 : public Observer {
public:
void update(const std::string& message) override {
std::cout << "ConcreteObserver2 received: " << message << std::endl;
}
};
class Subject {
public:
void attach(std::shared_ptr<Observer> observer) {
observers.push_back(observer);
}
void detach(std::shared_ptr<Observer> observer) {
observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
}
void notify(const std::string& message) {
for (const auto& observer : observers) {
observer->update(message);
}
}
private:
std::vector<std::shared_ptr<Observer>> observers;
};
int main() {
Subject subject;
std::shared_ptr<Observer> observer1 = std::make_shared<ConcreteObserver1>();
std::shared_ptr<Observer> observer2 = std::make_shared<ConcreteObserver2>();
subject.attach(observer1);
subject.attach(observer2);
subject.notify("State has changed!");
subject.detach(observer1);
subject.notify("Another update!");
return 0;
}
六. 智能指针
#include <iostream>
#include <mutex>
template <typename T>
class SafeUniquePtr {
public:
explicit SafeUniquePtr(T* ptr = nullptr) : pointer(ptr) {}
SafeUniquePtr(const SafeUniquePtr&) = delete;
SafeUniquePtr& operator=(const SafeUniquePtr&) = delete;
SafeUniquePtr(SafeUniquePtr&& other) {
std::lock_guard<std::mutex> lock(other.mtx);
pointer = other.pointer;
other.pointer = nullptr;
}
SafeUniquePtr& operator=(SafeUniquePtr&& other) {
if (this != &other) {
std::lock_guard<std::mutex> lock1(mtx);
std::lock_guard<std::mutex> lock2(other.mtx);
delete pointer;
pointer = other.pointer;
other.pointer = nullptr;
}
return *this;
}
T& operator*() {
std::lock_guard<std::mutex> lock(mtx);
return *pointer;
}
T* operator->() {
std::lock_guard<std::mutex> lock(mtx);
return pointer;
}
~SafeUniquePtr() {
std::lock_guard<std::mutex> lock(mtx);
delete pointer;
}
private:
T* pointer;
mutable std::mutex mtx;
};
七. 事务和分布式事务
BEGIN;
UPDATE A
SET balance = balance - 100
WHERE user_id = 1
AND balance >= 100;
IF ROW_COUNT() = 0 THEN
ROLLBACK;
SELECT '余额不足';
ELSE
UPDATE B
SET balance = balance + 100
WHERE user_id = 2;
COMMIT;
END IF;
START TRANSACTION;
UPDATE A
SET balance = balance - 100
WHERE user_id = 1
AND balance >= 100;
IF ROW_COUNT() = 0 THEN
ROLLBACK;
REPORT FAILURE TO COORDINATOR;
ELSE
PREPARE TRANSACTION 'txn1';
REPORT SUCCESS TO COORDINATOR;
END IF;
START TRANSACTION;
UPDATE B
SET balance = balance + 100
WHERE user_id = 2;
PREPARE TRANSACTION 'txn2';
COMMIT PREPARED 'txn1';
COMMIT PREPARED 'txn2';
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本