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

There may be a bug in GetOrInsert #81

Open
ssfyn opened this issue Dec 4, 2024 · 0 comments
Open

There may be a bug in GetOrInsert #81

ssfyn opened this issue Dec 4, 2024 · 0 comments
Labels

Comments

@ssfyn
Copy link

ssfyn commented Dec 4, 2024

Describe the bug
When multiple coroutines call GetOrInsert at the same time, data may be missed during Range query.

To Reproduce

func main() {
	m := hashmap.New[string, bool]()
	wg := sync.WaitGroup{}
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		kk := strconv.Itoa(i)
		go func() {
			m.GetOrInsert(kk, true)
			wg.Done()
		}()
	}
	wg.Wait()
	tmp := make([]string, 0)
	m.Range(func(key string, value bool) bool {
		tmp = append(tmp, key)
		return true
	})
	log.Println(len(tmp), "/",  m.Len()) // print: 9XX / 1000
}

Expected behavior
Return data correctly

System (please complete the following information):

  • OS: macos / linux
  • Version / Commit: 1.0.8

Additional context
When called repeatedly, Len() may be larger than the actual length.

func main() {
	m := hashmap.New[string, bool]()
	wg := sync.WaitGroup{}
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		kk := strconv.Itoa(i)
		go func() {
			m.GetOrInsert(kk, true) // call
			m.GetOrInsert(kk, true) // repeat call
			m.GetOrInsert(kk, true) // repeat call
			m.GetOrInsert(kk, true) // repeat call
			wg.Done()
		}()
	}
	wg.Wait()
	tmp := make([]string, 0)
	m.Range(func(key string, value bool) bool {
		tmp = append(tmp, key)
		return true
	})
	log.Println(m.Len()) // m.Len() may be > 1000
}
@ssfyn ssfyn added the bug label Dec 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant