惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
Blog — PlanetScale
Blog — PlanetScale
F
Fortinet All Blogs
腾讯CDC
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
WordPress大学
WordPress大学
雷峰网
雷峰网
小众软件
小众软件
D
DataBreaches.Net
V
Visual Studio Blog
博客园 - Franky
IT之家
IT之家
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
博客园 - 聂微东
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
G
Google Developers Blog
云风的 BLOG
云风的 BLOG

博客园 - ®Geovin Du Dream Park™

go: Functional Options Pattern go:Timing Functions Pattern python: Timing Functions Pattern go: Steady-State Pattern python: Steady-State Pattern go: Handshaking Pattern python: Handshaking Pattern go: Fail-Fast Pattern python: Fail-Fast Pattern I go: Deadline Pattern python: Deadline Pattern go: Circuit-Breaker Pattern python: Circuit-Breaker Pattern go: Bulkheads Pattern python: Bulkheads Pattern go: Push & Pull Pattern python: Push & Pull Pattern python: Publish/Subscribe Pattern II go: Publish/Subscribe Pattern python: Publish/Subscribe Pattern go: Futures & Promises Pattern python: Futures & Promises Pattern go: Worker Pool Pattern go:Pipeline Pattern python: Worker Pool Pattern python: Pipeline Pattern go: Fan-Out Pattern python: Fan-Out Pattern go: Fan-In Pattern python: Fan-In Pattern Fan-In
go: Read-Write Lock Pattern
®Geovin Du Dream Park™ · 2026-05-18 · via 博客园 - ®Geovin Du Dream Park™

项目结构:

image

/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: 读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 20:32
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : jewelry.go
*/
package model

import "sync"

// Jewelry 珠宝核心实体
type Jewelry struct {
	ID    string  `json:"id"`
	Name  string  `json:"name"`
	Type  string  `json:"type"` // 钻石/黄金/铂金
	Price float64 `json:"price"`
	Stock int     `json:"stock"`
}

// JewelryRepository 数据层接口(面向接口编程,可扩展存储:MySQL/Redis)
type JewelryRepository interface {
	GetJewelry(id string) (*Jewelry, error)
	ListJewelry() ([]*Jewelry, error)
	UpdateJewelry(j *Jewelry) error
}

// jewelryMemoryRepo 内存存储(使用读写锁保证并发安全)
type jewelryMemoryRepo struct {
	data map[string]*Jewelry
	mu   sync.RWMutex // 核心:读写锁
}
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 22:07 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry_service.py

import threading
from ReadWriteLockPattern.model.jewelry import Jewelry
from ReadWriteLockPattern.core.resource import ResourceManager



class JewelryService:
    """
    珠宝业务服务:读、写、查询完全分离
    """
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._init_data()
        return cls._instance

    def get_jewelry_list(self):
        """
        并行读:只输出内容,不重复打印标题
        :param self:
        :return:
        """
        self._lock.acquire_read()
        try:
            for j in self._jewelry_list:
                print(f"ID:{j.id} | {j.name} | 价格:{j.price} | 库存:{j.stock}")
        finally:
            self._lock.release_read()

    def print_title(self):
        """
        单独打印标题,保证输出格式精准
        :param self:
        :return:
        """
        print("======= 珠宝列表 =======")

    def _init_data(self):
        self._lock = ResourceManager().rw_lock
        self._jewelry_list = [
            Jewelry("J001", "一克拉钻石项链", 59999.99, 10)
        ]

    def print_and_get(self):
        self._lock.acquire_read()
        try:
            print("======= 珠宝列表 =======")
            for j in self._jewelry_list:
                print(f"ID:{j.id} | {j.name} | 价格:{j.price} | 库存:{j.stock}")
        finally:
            self._lock.release_read()

    def update_jewelry(self, jid: str, price: float, stock: int):
        self._lock.acquire_write()
        try:
            for j in self._jewelry_list:
                if j.id == jid:
                    j.price = price
                    j.stock = stock
                    print(f"✅ 珠宝[{jid}] 更新成功")
                    break
        finally:
            self._lock.release_write()
/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: 读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 20:35
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : jewelry_controller.go
*/
package controller

import (
	"fmt"
	//"godesginpattern/readwritelock/model"
	"godesginpattern/readwritelock/service"
)

type JewelryController struct {
	service *service.JewelryService
}

func NewJewelryController(svc *service.JewelryService) *JewelryController {
	return &JewelryController{service: svc}
}

func (c *JewelryController) ListJewelry() {
	list, err := c.service.ListAllJewelry()
	if err != nil {
		fmt.Println("查询失败:", err)
		return
	}
	fmt.Println("======= 珠宝列表 =======")
	for _, j := range list {
		fmt.Printf("ID:%s | %s | 价格:%.2f | 库存:%d\n",
			j.ID, j.Name, j.Price, j.Stock)
	}
}

func (c *JewelryController) UpdateJewelry(id string, price float64, stock int) {
	err := c.service.UpdateJewelryPriceStock(id, price, stock)
	if err != nil {
		fmt.Println("更新失败:", err)
		return
	}
	fmt.Printf("✅ 珠宝[%s] 更新成功\n", id)
}
/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: 读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 20:34
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : jewelry_repo.go
*/
package repository

import (
	"errors"
	"godesginpattern/readwritelock/model"
	"sync"
)

// jewelryMemoryRepo 实现了 model.JewelryRepository 接口
// 读写锁在这里定义!!!(之前放错位置导致报错)
type jewelryMemoryRepo struct {
	data map[string]*model.Jewelry
	mu   sync.RWMutex // 读写锁
}

// NewJewelryMemoryRepo 创建内存存储实例
func NewJewelryMemoryRepo() model.JewelryRepository {
	return &jewelryMemoryRepo{
		data: make(map[string]*model.Jewelry),
	}
}

// ==================== 读操作(并行) ====================
func (r *jewelryMemoryRepo) GetJewelry(id string) (*model.Jewelry, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	j, ok := r.data[id]
	if !ok {
		return nil, errors.New("珠宝不存在")
	}
	return j, nil
}

func (r *jewelryMemoryRepo) ListJewelry() ([]*model.Jewelry, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	list := make([]*model.Jewelry, 0, len(r.data))
	for _, j := range r.data {
		list = append(list, j)
	}
	return list, nil
}

// ==================== 写操作(独占) ====================
func (r *jewelryMemoryRepo) UpdateJewelry(j *model.Jewelry) error {
	r.mu.Lock()
	defer r.mu.Unlock()

	r.data[j.ID] = j
	return nil
}

调用:

/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: 读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 20:41
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : readwritelockbll.go

ReadWriteLock/
├── go.mod
├── main.go # 入口
│   ├── model/
│   │   └── jewelry.go # 只定义实体 + 接口
│   ├── repository/
│   │   └── jewelry_repo.go # 实现读写锁存储(真正放 jewelryMemoryRepo)
│   ├── service/
│   │   └── jewelry_service.go
│   └── controller/
│       └── jewelry_controller.go
*/
package bll

import (
	"fmt"
	"godesginpattern/readwritelock/controller"
	"godesginpattern/readwritelock/model"
	"godesginpattern/readwritelock/repository"
	"godesginpattern/readwritelock/service"
	"sync"
	"time"
)

func ReadWriteLockMain() {
	// 依赖注入
	repo := repository.NewJewelryMemoryRepo()
	svc := service.NewJewelryService(repo)
	ctl := controller.NewJewelryController(svc)

	// 初始化测试数据
	_ = repo.UpdateJewelry(&model.Jewelry{
		ID:    "J001",
		Name:  "一克拉钻石项链",
		Type:  "钻石",
		Price: 59999.99,
		Stock: 10,
	})

	var wg sync.WaitGroup

	fmt.Println("======== 高并发并行读(客户查看珠宝)========")
	for i := 1; i <= 10; i++ {
		wg.Add(1)
		go func(num int) {
			defer wg.Done()
			ctl.ListJewelry()
			time.Sleep(200 * time.Millisecond)
		}(i)
	}
	wg.Wait()

	fmt.Println("\n======== 独占写(商家修改价格)========")
	wg.Add(1)
	go func() {
		defer wg.Done()
		ctl.UpdateJewelry("J001", 49999.99, 8)
	}()
	wg.Wait()

	fmt.Println("\n======== 再次并行读 ========")
	for i := 1; i <= 5; i++ {
		wg.Add(1)
		go func(num int) {
			defer wg.Done()
			ctl.ListJewelry()
		}(i)
	}

	wg.Wait()
	fmt.Println("\n🎉 珠宝系统运行完成")
}

输出:

image

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)