-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
94 lines (80 loc) · 2.09 KB
/
Copy pathmain.go
File metadata and controls
94 lines (80 loc) · 2.09 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"sync"
)
type token struct {
data string
recipient int
ttl int
}
var wg sync.WaitGroup
func node(thread_index int, ch_resv chan token, ch_send chan token) {
defer wg.Done()
for { // waiting for any signal
message := <-ch_resv
if message.data == "qqq" {
break
}
fmt.Println("Thread ", thread_index, "| Recieved message.")
if message.recipient == thread_index {
fmt.Println("Thread ", thread_index, "|", message.data)
} else {
if message.ttl > 0 {
message.ttl -= 1
ch_send <- message
} else {
fmt.Println("Thread ", thread_index, "| Message expired.")
}
}
}
}
func main() {
fmt.Println("MAIN THREAD| Enter number of threads")
var threads_number int
fmt.Scanln(&threads_number)
// creating channels, 0 channel is reserved for talking with main thread
var channels []chan token = make([]chan token, threads_number)
var quit = make(chan int)
for i := 0; i < threads_number; i++ { // creating threads
channels[i] = make(chan token)
wg.Add(1)
}
for i := 0; i < threads_number; i++ {
if i == threads_number-1 {
go node(i, channels[i], channels[i]) // sending for last channel same channel bcs he never send msg to anyone
} else {
go node(i, channels[i], channels[i+1])
}
}
var new_token token
for threads_number > 0 {
fmt.Println("MAIN THREAD| Enter message data or write qqq to exit")
fmt.Scanln(&new_token.data)
if new_token.data == "qqq" {
channels[0] <- new_token
break
}
fmt.Println("MAIN THREAD| Enter recipient id (starting from 0)")
fmt.Scanln(&new_token.recipient)
for {
if new_token.recipient > len(channels)-1 {
fmt.Println("MAIN THREAD| This is now a valid recipient id! Try again! Avaliable ids: from 0 to ", len(channels)-1)
fmt.Scanln(&new_token.recipient)
} else {
break
}
}
fmt.Println("MAIN THREAD| Enter message timeout")
fmt.Scanln(&new_token.ttl)
channels[0] <- new_token
}
for i := 1; i < threads_number; i++ {
channels[i] <- new_token
}
wg.Wait()
for i := 1; i < threads_number; i++ { // creating threads
close(channels[i])
}
close(quit)
}