github.com/DARA-Project/GoDist-Scheduler@v0.0.0-20201030134746-668de4acea0d/examples/ProducerConsumer/ProducerConsumer.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"runtime"
     7  )
     8  
     9  type Consumer struct {
    10  	msgs *chan int
    11  }
    12  
    13  // NewConsumer creates a Consumer
    14  func NewConsumer(msgs *chan int) *Consumer {
    15  	return &Consumer{msgs: msgs}
    16  }
    17  
    18  // consume reads the msgs channel
    19  func (c *Consumer) consume() {
    20  	fmt.Println("[consume]: Started")
    21  	for {
    22  		msg := <-*c.msgs
    23  		fmt.Println("[consume]: Received:", msg)
    24  	}
    25  }
    26  
    27  // Producer definition
    28  type Producer struct {
    29  	msgs *chan int
    30  	done *chan bool
    31  }
    32  
    33  // NewProducer creates a Producer
    34  func NewProducer(msgs *chan int, done *chan bool) *Producer {
    35  	return &Producer{msgs: msgs, done: done}
    36  }
    37  
    38  // produce creates and sends the message through msgs channel
    39  func (p *Producer) produce(max int) {
    40  	fmt.Println("[produce]: Started")
    41  	for i := 0; i < max; i++ {
    42  		fmt.Println("[produce]: Sending ", i)
    43  		*p.msgs <- i
    44  	}
    45  	*p.done <- true // signal when done
    46  	fmt.Println("[produce]: Done")
    47  }
    48  
    49  func main() {
    50  
    51  	// get the maximum number of messages from flags
    52  	max := flag.Int("n", 5, "defines the number of messages")
    53  
    54  	flag.Parse()
    55  
    56  	var msgs = make(chan int)  // channel to send messages
    57  	var done = make(chan bool) // channel to control when production is done
    58  
    59  	// Start a goroutine for Produce.produce
    60  	go NewProducer(&msgs, &done).produce(*max)
    61  
    62  	// Start a goroutine for Consumer.consume
    63  	go NewConsumer(&msgs).consume()
    64  
    65  	// Finish the program when the production is done
    66  	<-done
    67  
    68  	runtime.DaraLog("FinalCheck", "NumSendings,NumDeliveries", runtime.NumSendings(msgs), runtime.NumDeliveries(msgs))
    69  }