File: bytesemaphore.go

package info (click to toggle)
syncthing 1.0.0~ds1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 11,096 kB
  • sloc: xml: 1,028; sh: 219; makefile: 61
file content (70 lines) | stat: -rw-r--r-- 1,245 bytes parent folder | download
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright (C) 2018 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package model

import (
	"sync"
)

type byteSemaphore struct {
	max       int
	available int
	mut       sync.Mutex
	cond      *sync.Cond
}

func newByteSemaphore(max int) *byteSemaphore {
	s := byteSemaphore{
		max:       max,
		available: max,
	}
	s.cond = sync.NewCond(&s.mut)
	return &s
}

func (s *byteSemaphore) take(bytes int) {
	s.mut.Lock()
	if bytes > s.max {
		bytes = s.max
	}
	for bytes > s.available {
		s.cond.Wait()
		if bytes > s.max {
			bytes = s.max
		}
	}
	s.available -= bytes
	s.mut.Unlock()
}

func (s *byteSemaphore) give(bytes int) {
	s.mut.Lock()
	if bytes > s.max {
		bytes = s.max
	}
	if s.available+bytes > s.max {
		s.available = s.max
	} else {
		s.available += bytes
	}
	s.cond.Broadcast()
	s.mut.Unlock()
}

func (s *byteSemaphore) setCapacity(cap int) {
	s.mut.Lock()
	diff := cap - s.max
	s.max = cap
	s.available += diff
	if s.available < 0 {
		s.available = 0
	} else if s.available > s.max {
		s.available = s.max
	}
	s.cond.Broadcast()
	s.mut.Unlock()
}