Skip to content

fix: correct RLock scope in Context.Copy method #4166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

1911860538
Copy link
Contributor

No description provided.

@NezhaFan
Copy link
Contributor

You are wrong, must add a read lock during the loop to prevent writing at this time. and maybe you don't understand the copy of map .

@1911860538
Copy link
Contributor Author

You are wrong, must add a read lock during the loop to prevent writing at this time. and maybe you don't understand the copy of map .

c.mu.RLock() is used to protect c.Keys, not cp.Keys. cp.Keys does not require lock protection here because the Copy method is in the process of creating cp, so there is no read-write race condition for cp.Keys.Since the Copy method involves reading operations on c.Keys, my modification poses no issues.

@NezhaFan
Copy link
Contributor

NezhaFan commented Mar 23, 2025

我觉得你在理解map拷贝或者读写锁 不太对。 m2 := m1 不需要加锁,只是拷贝了 map 的结构体。 对于 map 读写考虑并发的情况下,要加锁。

func main() {
	var mu sync.RWMutex
	n := 50000

	m1 := make(map[int]int, n)
	for i := 0; i < n; i++ {
		m1[i] = i
	}

	// 并发写入
	for i := 0; i < n; i++ {
		go func(i int) {
			mu.Lock()
			defer mu.Unlock()
			m1[i] = i
		}(i)
	}


        // 你的意思:直接赋值拷贝加锁
	mu.RLock()
	m2 := m1
	mu.RUnlock()

        // 应该这样:读的过程前后锁
        // mu.RLock()
	// 拷贝
	cp := make(map[int]int, n)
	for k, v := range m2 {
		cp[k] = v
	}
	// mu.RUnlock()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants