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

proposal: sync: add SafeLength and DirtyLength. #53903

Closed
sivchari opened this issue Jul 15, 2022 · 1 comment
Closed

proposal: sync: add SafeLength and DirtyLength. #53903

sivchari opened this issue Jul 15, 2022 · 1 comment

Comments

@sivchari
Copy link
Contributor

I propose to add SafeLength and DirtyLength method to sync.Map. Currently, we don't get the length of sync.Map. For that reason, we can't prepare length and capacity for map and slice. sync.Map has two map, m contained in readOnly struct and dirty.

So, SafeLength returns the length of m, DirtyLength returns the length of dirty. If a developer wanna get the length of m (i.e. wanna to get the length of immutable struct stored atomically), we'll use SafeLength. Conversely, If a developer wanna to get the length of dirty which contains all values, we'll use DirtyLength.

But, dirty may be initialized. For example, Load and missLocked initialize it. Above the reason, I recommend to use SafeLength, but I also added DirtyLength for every case. If this proposal is accepted, we can execute following code.

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	m := sync.Map{}

	m.Store("Key 1", "Value 1")
	m.Store("Key 2", "Value 2")
	m.Store("Key 3", "Value 3")
	m.Store("Key 4", "Value 4")
	m.Store("Key 5", "Value 5")

	<-time.After(5 * time.Millisecond)

	vals := make([]string, 0, m.SafeLength())

	m.Range(func(key interface{}, value interface{}) bool {
		vals = append(vals, value.(string))
		return true
	})

	fmt.Println(vals)
}
@gopherbot gopherbot added this to the Proposal milestone Jul 15, 2022
@seankhliao
Copy link
Member

Duplicate of #20680

@seankhliao seankhliao marked this as a duplicate of #20680 Jul 15, 2022
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Jul 15, 2022
@golang golang locked and limited conversation to collaborators Jul 15, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants