summaryrefslogtreecommitdiff
path: root/forks.go
diff options
context:
space:
mode:
Diffstat (limited to 'forks.go')
-rw-r--r--forks.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/forks.go b/forks.go
new file mode 100644
index 0000000..ba57ef7
--- /dev/null
+++ b/forks.go
@@ -0,0 +1,33 @@
+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) Grab() {
+ <-f
+}
+
+func (f Fork) TryGrab(d time.Duration) bool {
+ select {
+ case <-f:
+ return true
+ case <-time.After(d):
+ return false
+ }
+}
+
+func (f Fork) Put() {
+ f <- struct{}{}
+}