summaryrefslogtreecommitdiff
path: root/forks.go
blob: d45fd3b387e2c8d366b96508b0fc3e60fcd79bf2 (plain)
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
package main

import "time"

type Fork chan struct{}

func NewForks(n int) []Fork {
	forks := make([]Fork, n)

	for i := range forks {
		forks[i] = make(Fork, 1)
		forks[i].Put()
	}

	return forks
}

func (f Fork) Put() { f <- struct{}{} }
func (f Fork) Get() { <-f }

func (f Fork) TryGet(d time.Duration) bool {
	select {
	case <-f:
		return true
	case <-time.After(d):
		return false
	}
}