File: cond.go

package info (click to toggle)
golang-github-ngaut-sync2 0.0~git20141008.0.7a24ed7-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 96 kB
  • sloc: makefile: 3
file content (56 lines) | stat: -rw-r--r-- 877 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright 2013, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package sync2

import (
	"sync"
)

// Cond is an alternate implementation of sync.Cond
type Cond struct {
	L       sync.Locker
	sema    chan struct{}
	waiters AtomicInt64
}

func NewCond(l sync.Locker) *Cond {
	return &Cond{L: l, sema: make(chan struct{})}
}

func (c *Cond) Wait() {
	c.waiters.Add(1)
	c.L.Unlock()
	<-c.sema
	c.L.Lock()
}

func (c *Cond) Signal() {
	for {
		w := c.waiters.Get()
		if w == 0 {
			return
		}
		if c.waiters.CompareAndSwap(w, w-1) {
			break
		}
	}
	c.sema <- struct{}{}
}

func (c *Cond) Broadcast() {
	var w int64
	for {
		w = c.waiters.Get()
		if w == 0 {
			return
		}
		if c.waiters.CompareAndSwap(w, 0) {
			break
		}
	}
	for i := int64(0); i < w; i++ {
		c.sema <- struct{}{}
	}
}