cond

package
v0.0.0-...-50b27ac Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2023 License: MIT Imports: 0 Imported by: 0

README

cond

sync.Cond — примитив синхронизации для эффективных межгорутинных нотификаций.

Обычно использование выглядит так: одни горутины ждут выполнения некоторого условия, а другие горутины выполняют это условие и информируют ждущих.

Что нужно сделать?

Нужно написать реализацию Cond, используя каналы.

Использование пакета sync в этой задаче запрещено!

type Cond struct {
	L Locker
}

func New(l Locker) *Cond {}

func (c *Cond) Wait() {}
func (c *Cond) Signal() {}
func (c *Cond) Broadcast() {}

Locker это sync.Locker, но мы не хотим использовать sync.

У каждого Cond есть блокировка L, передающаяся в конструкторе. Cond поддерживает FIFO очередь ожидающих горутин.

  • Wait() паникует, если L не взята.
  • Wait() добавляет текущую горутину в очередь, возвращает блокировку L, блокирует текущую горутину. Заснувшая горутина может быть разбужена другой горутиной через вызов Signal() или Broadcast(). При просыпании засыпавшая горутина продолжит исполнение, возьмёт L и завершит вызов Wait().
  • Signal() извлекает и разблокирует первую блокировку из очереди, если такая есть, иначе no-op.
  • Broadcast() извлекает и разблокирует все блокировки из очереди. no-op, если очередь пустая.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cond

type Cond struct {
	L Locker
}

Cond implements a condition variable, a rendezvous point for goroutines waiting for or announcing the occurrence of an event.

Each Cond has an associated Locker L (often a *sync.Mutex or *sync.RWMutex), which must be held when changing the condition and when calling the Wait method.

func New

func New(l Locker) *Cond

New returns a new Cond with Locker l.

func (*Cond) Broadcast

func (c *Cond) Broadcast()

Broadcast wakes all goroutines waiting on c.

It is allowed but not required for the caller to hold c.L during the call.

func (*Cond) Signal

func (c *Cond) Signal()

Signal wakes one goroutine waiting on c, if there is any.

It is allowed but not required for the caller to hold c.L during the call.

func (*Cond) Wait

func (c *Cond) Wait()

Wait atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning. Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal.

Because c.L is not locked when Wait first resumes, the caller typically cannot assume that the condition is true when Wait returns. Instead, the caller should Wait in a loop:

c.L.Lock()
for !condition() {
    c.Wait()
}
... make use of condition ...
c.L.Unlock()

type Locker

type Locker interface {
	Lock()
	Unlock()
}

A Locker represents an object that can be locked and unlocked.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL