Skip to content

crux: concurrent state using channels #223

@skhal

Description

@skhal

A conventional pattern is to use a mutual exclusion (mutex) to protect access to some state in concurrent applications:

type Fooer struct {
  mu sync.Mutex
  st *state
}
func (f *Fooer) Foo() {
  mu.Lock()
  defer mu.Unlock()
  use(f.st)
}

There is a way to achieve the same effect without mutex, using channels:

type Fooer struct {
  st chan *state // must be buffered to store the state
}
func (f *Fooer) Foo() {
  st <-f.st
  defer func() { f.st<- st }()
  use(st)
}

It is easy to add context.Context to the new architecture to avoid locking in attempt to acquire the state.

Metadata

Metadata

Assignees

No one assigned

    Labels

    newNew binary, feature, functionality.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions