'Best way of locking something in a slice

So i have a slice that contains a struct. I want to randomly pull from that slice and lock that struct from being able to be used until it is unlocked. What is the best way to go about this? Ive done the randomly picking but how should i lock the struct? i was thinking maybe a mutex?

go


Solution 1:[1]

If you want to change struct fields in parallel, you may put sync.Mutex into struct like this:

type User struct {
    mu sync.RWMutex
    ID int64
}

Or you may store some mutex'es separately. Just check the cost of many mutex'es against one for your application.

If you plan to use slice in parallel to, you need to use one more mutex for slice.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thrownew