Home >Backend Development >Golang >Producer/Consumer
We consider two processes, called “producer” and “consumer”, respectively. The producer is a cyclical process and each time it goes through its cycle it produces a certain portion of information, which must be processed by the consumer. The consumer is also a cyclical process and each time it goes through its cycle it can process the next piece of information, as it was produced by the producer. A simple example is given by a computational process, which produces as “portions of information” images of punched cards to be punched by a punched card, which plays the role of the consumer.[1]
A producer creates items and stores them in a data structure, while a consumer removes items from that structure and processes them.
If consumption is greater than production, the buffer (data structure) empties, and the consumer has nothing to consume
If consumption is less than production, the buffer fills up, and the producer is unable to add more items. This is a classic problem called limited buffer.
Suppose we have a producer that publishes an email in the buffer, and a consumer that consumes the email from the buffer and displays a message stating that an email was sent with the new access password for the email. email informed.
package main import ( "fmt" "os" "strconv" "sync" "time" ) type buffer struct { items []string mu sync.Mutex } func (buff *buffer) add(item string) { buff.mu.Lock() defer buff.mu.Unlock() if len(buff.items) < 5 { buff.items = append(buff.items, item) // fmt.Println("Foi adicionado o item " + item) } else { fmt.Println("O Buffer não pode armazenar nenhum item mais está com a capacidade máxima") os.Exit(0) } } func (buff *buffer) get() string { buff.mu.Lock() defer buff.mu.Unlock() if len(buff.items) == 0 { return "" } target := buff.items[0] buff.items = buff.items[1:] return target } var wg sync.WaitGroup func main() { buff := buffer{} wg.Add(2) go producer(&buff) go consumer(&buff) wg.Wait() } func producer(buff *buffer) { defer wg.Done() for index := 1; ; index++ { str := strconv.Itoa(index) + "@email.com" buff.add(str) time.Sleep(5 * time.Millisecond) // Adiciona um pequeno atraso para simular produção } } func consumer(buff *buffer) { defer wg.Done() for { data := buff.get() if data != "" { fmt.Println("Enviado um email com a nova senha de acesso para: " + data) } } }
Code link: https://github.com/jcelsocosta/race_condition/blob/main/producerconsumer/buffer/producerconsumer.go
https://www.cin.ufpe.br/~cagf/if677/2015-2/slides/08_Concorrencia%20(Jorge).pdf
The above is the detailed content of Producer/Consumer. For more information, please follow other related articles on the PHP Chinese website!