1 /* pc_channel_multi.go */
12 func random_between (begin
, end
int64) int64 {
13 random_byte
:= make([]byte, 1)
14 rand
.Read(random_byte
)
15 return int64(random_byte
[0]) % (end
- begin
+ 1) + begin
18 func random_sleep () {
19 time
.Sleep(random_between(0, *MAX_SLEEP_TIME
) * 10e7
)
22 func send (channel
chan int, i
int) {
26 func recv (channel
chan int) int {
30 func signal (channel
chan int) {
31 if len(channel
) < cap(channel
) ||
cap(channel
) == 0 {
36 func wait (channel
chan int) {
41 BUFFER_SIZE
= flag
.Int("s", 5, "BUFFER_SIZE") // flag -s
42 MAX_SLEEP_TIME
= flag
.Int64("t", 5, "MAX_SLEEP_TIME") // flag -t
43 MAX_PRODUCTIONS
= flag
.Int("m", 0, "MAX_PRODUCTIONS, 0 for infinity") // flag -m
44 N_PRODUCERS
= flag
.Int("p", 3, "N_PRODUCERS") // flag -p
45 N_CONSUMERS
= flag
.Int("c", 3, "N_CONSUMERS") // flag -c
46 pipe
= make(chan int, *BUFFER_SIZE
)
50 func producer (id
int) {
51 for i
:= 0; i
< *MAX_PRODUCTIONS ||
*MAX_PRODUCTIONS
== 0; i
++ {
52 Println(id
, "producing:", i
+ id
* 1e5
)
53 send(pipe
, i
+ id
* 1e5
)
59 func consumer (id
int) {
62 if closed(pipe
) { // canal fechado?
65 Println("\t\t\t", id
, "consuming:", v
)
72 flag
.Parse() // processa flags
73 Println("BUFFER_SIZE =", *BUFFER_SIZE
)
74 Println("MAX_SLEEP_TIME =", *MAX_SLEEP_TIME
)
75 Println("MAX_PRODUCTIONS =", *MAX_PRODUCTIONS
)
76 Println("N_PRODUCERS =", *N_PRODUCERS
)
77 Println("N_CONSUMERS =", *N_CONSUMERS
)
78 for i
:= 0; i
< *N_PRODUCERS
; i
++ { // cria produtores
81 for i
:= 0; i
< *N_CONSUMERS
; i
++ { // cria consumidores
84 for i
:= 0; i
< *N_PRODUCERS
; i
++ { // espera o término dos produtores
87 close(pipe
) // fecha comunicação
88 for i
:= 0; i
< *N_CONSUMERS
; i
++ { // espera o término dos consumidores