-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect.go
54 lines (50 loc) · 1005 Bytes
/
select.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
52
53
54
/*
Program select prikazuje uporabo stavka select pri delu s kanali v programskem jeziku go
*/
package main
import (
"fmt"
"time"
)
// Funkcija, ki čaka na pritisk tipke "Enter"
func readKey(input chan bool) {
fmt.Scanln()
input <- true
}
// Delavec
func worker(id int, done chan bool) {
fmt.Print("Delavec ", id)
time.Sleep(2 * time.Second)
fmt.Print("Končal")
done <- true
}
func main() {
input := make(chan bool)
done := make(chan bool)
w := 0
// Zaženemo gorutino, ki čaka na pritisk tipke
go readKey(input)
// Zaženemo prvega delavca
go worker(w, done)
// Anonimna funkcija z neskončno zanko
func() {
for {
select {
// Pritisk tipke: končamo
case <-input:
return
// Delavec zaključil, zaženimo novega
case <-done:
fmt.Println()
w = w + 1
go worker(w, done)
// Če se nič ne zgodi izvedemo privzeto akcijo
default:
time.Sleep(200 * time.Millisecond)
fmt.Print(".")
}
}
}()
// Počakamo na zadnjega delavca
<-done
}