-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchannels.go
51 lines (45 loc) · 1.04 KB
/
channels.go
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
//
// This file is part of go-algorithms.
//
// Copyright 2024 Cristian Maglie. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
package f
import "sync"
// DiscardCh consumes all incoming messages from the given channel until it's closed.
func DiscardCh[T any](ch <-chan T) {
for range ch {
}
}
// Future is an object that holds a result value. The value may be read and
// written asynchronously.
type Future[T any] struct {
lock sync.Mutex
set bool
cond *sync.Cond
value T
}
// Send a result in the Future. Threads waiting for result will be unlocked.
func (f *Future[T]) Send(value T) {
f.lock.Lock()
defer f.lock.Unlock()
f.set = true
f.value = value
if f.cond != nil {
f.cond.Broadcast()
f.cond = nil
}
}
// Await for a result from the Future, blocks until a result is available.
func (f *Future[T]) Await() T {
f.lock.Lock()
defer f.lock.Unlock()
for !f.set {
if f.cond == nil {
f.cond = sync.NewCond(&f.lock)
}
f.cond.Wait()
}
return f.value
}