From ec1f07fe7253a457b44ef06e7bc206f459ead76d Mon Sep 17 00:00:00 2001 From: zhangkun Date: Fri, 14 Nov 2025 17:55:07 +0800 Subject: [PATCH] fix: add thread safety to brightness calculation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added mutex lock to protect shared variables totalBrightness and pixCount in isTooBright function. The imaging.AdjustFunc processes pixels concurrently, which could cause race conditions when multiple goroutines access and modify these shared variables simultaneously. This ensures thread-safe calculation of average brightness when determining if an image is too bright. Influence: 1. Test image brightness detection with various image types and sizes 2. Verify that concurrent image processing does not cause race conditions 3. Ensure brightness calculation remains accurate under multi-threaded scenarios 4. Test with both bright and dark images to confirm proper functionality fix: 为亮度计算添加线程安全保护 在 isTooBright 函数中添加互斥锁保护共享变量 totalBrightness 和 pixCount。由于 imaging.AdjustFunc 会并发处理像素,当多个 goroutine 同时 访问和修改这些共享变量时可能导致竞态条件。这确保了在确定图像是否过亮时, 平均亮度的计算是线程安全的。 Influence: 1. 测试各种图像类型和大小的亮度检测功能 2. 验证并发图像处理不会导致竞态条件 3. 确保在多线程场景下亮度计算保持准确 4. 使用亮图和暗图测试以确认功能正常 --- blurimage/blurimage.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/blurimage/blurimage.go b/blurimage/blurimage.go index ea86677..caf572f 100644 --- a/blurimage/blurimage.go +++ b/blurimage/blurimage.go @@ -10,6 +10,7 @@ import ( "os" "path" "runtime/debug" + "sync" "github.com/disintegration/imaging" ) @@ -40,12 +41,14 @@ func BlurImage(file string, sigma float64, dest string) error { func isTooBright(img image.Image) bool { var pixCount float64 = 0 var totalBrightness float64 = 0 + var mu sync.Mutex imaging.AdjustFunc(img, func(c color.NRGBA) color.NRGBA { brightness := 0.2126*float64(c.R) + 0.7152*float64(c.G) + 0.0722*float64(c.B) + mu.Lock() totalBrightness += brightness pixCount++ - + mu.Unlock() return c })