3 [[http://golang.org/|Go]]: [[wp>Go_(programming_language)|Go]]
22 package main // executável principal sempre deve pertencer a este pacote
24 import . "fmt" // importa funções de saída formatada (Printf)
26 // função principal (como em C)
28 //sem o . no import teríamos que utilizar fmt.Printf
29 Printf("hello, world\n")
33 <file c producer_consumer.go>
34 /* pc_channel_multi.go */
45 func random_between (begin, end int64) int64 {
46 random_byte := make([]byte, 1)
47 rand.Read(random_byte)
48 return int64(random_byte[0]) % (end - begin + 1) + begin
51 func random_sleep () {
52 time.Sleep(random_between(0, *MAX_SLEEP_TIME) * 10e7)
55 func send (channel chan int, i int) {
59 func recv (channel chan int) int {
63 func signal (channel chan int) {
64 if len(channel) < cap(channel) || cap(channel) == 0 {
69 func wait (channel chan int) {
74 BUFFER_SIZE = flag.Int("s", 5, "BUFFER_SIZE") // flag -s
75 MAX_SLEEP_TIME = flag.Int64("t", 5, "MAX_SLEEP_TIME") // flag -t
76 MAX_PRODUCTIONS = flag.Int("m", 0, "MAX_PRODUCTIONS, 0 for infinity") // flag -m
77 N_PRODUCERS = flag.Int("p", 3, "N_PRODUCERS") // flag -p
78 N_CONSUMERS = flag.Int("c", 3, "N_CONSUMERS") // flag -c
79 pipe = make(chan int, *BUFFER_SIZE)
83 func producer (id int) {
84 for i := 0; i < *MAX_PRODUCTIONS || *MAX_PRODUCTIONS == 0; i++ {
85 Println(id, "producing:", i + id * 1e5)
86 send(pipe, i + id * 1e5)
92 func consumer (id int) {
95 if closed(pipe) { // canal fechado?
98 Println("\t\t\t", id, "consuming:", v)
105 flag.Parse() // processa flags
106 Println("BUFFER_SIZE =", *BUFFER_SIZE)
107 Println("MAX_SLEEP_TIME =", *MAX_SLEEP_TIME)
108 Println("MAX_PRODUCTIONS =", *MAX_PRODUCTIONS)
109 Println("N_PRODUCERS =", *N_PRODUCERS)
110 Println("N_CONSUMERS =", *N_CONSUMERS)
111 for i := 0; i < *N_PRODUCERS; i++ { // cria produtores
114 for i := 0; i < *N_CONSUMERS; i++ { // cria consumidores
117 for i := 0; i < *N_PRODUCERS; i++ { // espera o término dos produtores
120 close(pipe) // fecha comunicação
121 for i := 0; i < *N_CONSUMERS; i++ { // espera o término dos consumidores