Skip to content
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

why release lock reverse order in RWUnLocks #207

Closed
liamgheng opened this issue Nov 27, 2023 · 1 comment
Closed

why release lock reverse order in RWUnLocks #207

liamgheng opened this issue Nov 27, 2023 · 1 comment

Comments

@liamgheng
Copy link

func (dict *ConcurrentDict) RWLocks(writeKeys []string, readKeys []string) {
	keys := append(writeKeys, readKeys...)

        // Lock in normal order
	indices := dict.toLockIndices(keys, false)

	writeIndexSet := make(map[uint32]struct{})
	for _, wKey := range writeKeys {
		idx := dict.spread(fnv32(wKey))
		writeIndexSet[idx] = struct{}{}
	}
	for _, index := range indices {
		_, w := writeIndexSet[index]
		mu := &dict.table[index].mutex
		if w {
			mu.Lock()
		} else {
			mu.RLock()
		}
	}
}

// RWUnLocks unlocks write keys and read keys together. allow duplicate keys
func (dict *ConcurrentDict) RWUnLocks(writeKeys []string, readKeys []string) {
	keys := append(writeKeys, readKeys...)
        // Unlock in reverse order
	indices := dict.toLockIndices(keys, true)
	writeIndexSet := make(map[uint32]struct{})
	for _, wKey := range writeKeys {
		idx := dict.spread(fnv32(wKey))
		writeIndexSet[idx] = struct{}{}
	}
	for _, index := range indices {
		_, w := writeIndexSet[index]
		mu := &dict.table[index].mutex
		if w {
			mu.Unlock()
		} else {
			mu.RUnlock()
		}
	}
}

why release lock reverse order in RWUnLocks?
Or If release lock in normal or random order,can cause some race problem?

Thanks

@HDT3213
Copy link
Owner

HDT3213 commented Dec 11, 2023

That , Thread 1 locks in the order of A-B,and thread 2 locks in the order of B-A, will cause a deadlock.Therefore, the same order must be used for locking. The reverse order of unlocking and locking is just in case.

@HDT3213 HDT3213 closed this as completed May 23, 2024
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

No branches or pull requests

2 participants