Skip to content

Commit 18d1207

Browse files
mhduiy18202781743
authored andcommitted
fix: add thread safety to brightness calculation
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. 使用亮图和暗图测试以确认功能正常
1 parent 51d1a75 commit 18d1207

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

blurimage/blurimage.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"os"
1111
"path"
1212
"runtime/debug"
13+
"sync"
1314

1415
"github.com/disintegration/imaging"
1516
)
@@ -40,12 +41,14 @@ func BlurImage(file string, sigma float64, dest string) error {
4041
func isTooBright(img image.Image) bool {
4142
var pixCount float64 = 0
4243
var totalBrightness float64 = 0
44+
var mu sync.Mutex
4345

4446
imaging.AdjustFunc(img, func(c color.NRGBA) color.NRGBA {
4547
brightness := 0.2126*float64(c.R) + 0.7152*float64(c.G) + 0.0722*float64(c.B)
48+
mu.Lock()
4649
totalBrightness += brightness
4750
pixCount++
48-
51+
mu.Unlock()
4952
return c
5053
})
5154

0 commit comments

Comments
 (0)