Skip to content

Deadlock risk in threadsafe set #163

@rickb777

Description

@rickb777

Many of the methods in the threadsafe set use the obvious pattern

s.Lock()
o.Lock()

...  do something

s.Unlock()
o.Unlock()

This can deadlock if two goroutines are concurrently doing similar operations but with the operands reversed.

The standard solution derives from database locks and is to release locks in the opposite order. I think this is called the Resource Allocation Protocol but my recollection is hazy.

If you were to use defer always, then you would get this for free, i.e.

s.Lock()
defer s.Unlock()
o.Lock()
defer o.Unlock()

...  do something

This should be free from this kind of deadlock because the defer stack calls its functions in reverse order.

However, to reduce the chance this bug might creep back in later, it might be preferable to make the issue explicit like this.

s.Lock()
o.Lock()

...  do something

o.Unlock() // unlock o first to avoid deadlock
s.Unlock()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions