From 7ef80e84bfdc93f27e4e832cb8c64ec14d9d6553 Mon Sep 17 00:00:00 2001 From: Gustavo Kuklinski Date: Sat, 16 Feb 2019 19:31:57 -0200 Subject: [PATCH] =?UTF-8?q?Tradu=C3=A7=C3=A3o=20ddas=20Concorrencias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tradução da páginas de concorrencias em Go --- pt-br/02.7.md | 96 +++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/pt-br/02.7.md b/pt-br/02.7.md index dd6ecf52..e97dabb5 100644 --- a/pt-br/02.7.md +++ b/pt-br/02.7.md @@ -1,16 +1,16 @@ -# Concurrency +# Concorrência -It is said that Go is the C language of the 21st century. I think there are two reasons: first, Go is a simple language; second, concurrency is a hot topic in today's world, and Go supports this feature at the language level. +Diz-se que Go é a linguagem C do século XXI. Eu acho que existem duas razões: primeiro, o Go é uma linguagem simples; segundo, a simultaneidade é um tema importante no mundo atual, e o Go suporta esse recurso no nível da linguagem. ## goroutine -goroutines and concurrency are built into the core design of Go. They're similar to threads but work differently. More than a dozen goroutines maybe only have 5 or 6 underlying threads. Go also gives you full support to sharing memory in your goroutines. One goroutine usually uses 4~5 KB of stack memory. Therefore, it's not hard to run thousands of goroutines on a single computer. A goroutine is more lightweight, more efficient and more convenient than system threads. +goroutines e simultaneidade são incorporados ao design central do Go. Eles são semelhantes aos tópicos, mas funcionam de maneira diferente. Mais de uma dúzia de goroutines talvez tenham apenas 5 ou 6 threads subjacentes. Go também lhe dá suporte total para compartilhar memória em seus goroutines. Uma goroutine geralmente usa 4 ~ 5 KB de memória de pilha. Portanto, não é difícil executar milhares de goroutines em um único computador. Uma goroutine é mais leve, mais eficiente e mais conveniente que os threads do sistema. -goroutines run on the thread manager at runtime in Go. We use the `go` keyword to create a new goroutine, which is a function at the underlying level ( ***main() is a goroutine*** ). +Os goroutines são executados no gerenciador de encadeamentos em tempo de execução no Go. Usamos a palavra-chave `go` para criar uma nova goroutine, que é uma função no nível subjacente (*** main () é uma goroutine ***). go hello(a, b, c) -Let's see an example. +Vamos ao exemplo: package main @@ -31,7 +31,7 @@ Let's see an example. say("hello") // current goroutine } -Output: +Retorno hello world @@ -43,26 +43,26 @@ Output: world hello -We see that it's very easy to use concurrency in Go by using the keyword `go`. In the above example, these two goroutines share some memory, but we would better off following the design recipe: Don't use shared data to communicate, use communication to share data. +Vemos que é muito fácil usar a simultaneidade no Go usando a palavra-chave `go`. No exemplo acima, essas duas goroutines compartilham alguma memória, mas seria melhor seguir a receita de design: Não use dados compartilhados para se comunicar, use a comunicação para compartilhar dados. -runtime.Gosched() means let the CPU execute other goroutines, and come back at some point. +runtime.Gosched () significa deixar a CPU executar outras goroutines e voltar em algum momento. -The scheduler only uses one thread to run all goroutines, which means it only implements concurrency. If you want to use more CPU cores in order to take advantage of parallel processing, you have to call runtime.GOMAXPROCS(n) to set the number of cores you want to use. If `n<1`, it changes nothing. This function may be removed in the future, see more details about parallel processing and concurrency in this [article](http://concur.rspace.googlecode.com/hg/talk/concur.html#landing-slide). +O agendador usa apenas um thread para executar todos os goroutines, o que significa que ele apenas implementa a simultaneidade. Se você deseja usar mais núcleos de CPU para aproveitar o processamento paralelo, é necessário chamar runtime.GOMAXPROCS (n) para definir o número de núcleos que deseja usar. Se `n <1`, nada muda. Esta função pode ser removida no futuro, veja mais detalhes sobre o processamento paralelo e simultaneidade neste [artigo(em inglês)](http://concur.rspace.googlecode.com/hg/talk/concur.html#landing-slide). -## channels +## Canais(Channels) -goroutines run in the same memory address space, so you have to maintain synchronization when you want to access shared memory. How do you communicate between different goroutines? Go uses a very good communication mechanism called `channel`. `channel` is like a two-way pipeline in Unix shells: use `channel` to send or receive data. The only data type that can be used in channels is the type `channel` and the keyword `chan`. Be aware that you have to use `make` to create a new `channel`. +Os goroutines são executados no mesmo espaço de endereço de memória, portanto, você precisa manter a sincronização quando quiser acessar a memória compartilhada. Como você se comunica entre diferentes goroutines? Go usa um mecanismo de comunicação muito bom chamado `channel`. `channel` é como um pipeline bidirecional em shells Unix: use` channel` para enviar ou receber dados. O único tipo de dado que pode ser usado em canais é o tipo `channel` e a palavra-chave` chan`. Esteja ciente de que você tem que usar `make` para criar um novo` channel`. ci := make(chan int) cs := make(chan string) cf := make(chan interface{}) -channel uses the operator `<-` to send or receive data. +canais usa, o operador `<-` para enviar ou receber dados. - ch <- v // send v to channel ch. - v := <-ch // receive data from ch, and assign to v + ch <- v // envia v para o canal ch. + v := <-ch // recebe dados de ch, e os assina em v -Let's see more examples. +Exemplos: package main @@ -73,7 +73,7 @@ Let's see more examples. for _, v := range a { total += v } - c <- total // send total to c + c <- total // envia o total para c } func main() { @@ -82,39 +82,39 @@ Let's see more examples. c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) - x, y := <-c, <-c // receive from c + x, y := <-c, <-c // recebe de c fmt.Println(x, y, x + y) } -Sending and receiving data in channels blocks by default, so it's much easier to use synchronous goroutines. What I mean by block is that a goroutine will not continue when receiving data from an empty channel, i.e (`value := <-ch`), until other goroutines send data to this channel. On the other hand, the goroutine will not continue until the data it sends to a channel, i.e (`ch<-5`), is received. +Enviando e recebendo dados em blocos de canais por padrão, é muito mais fácil usar goroutines síncronas. O que quero dizer com block é que uma goroutine não continuará ao receber dados de um canal vazio, ou seja, (`value: = <-ch`), até que outras goroutines enviem dados para este canal. Por outro lado, a goroutine não continuará até que os dados enviados a um canal, ou seja (`ch <-5`), sejam recebidos. -## Buffered channels +## Canais em Buffer -I introduced non-buffered channels above. Go also has buffered channels that can store more than a single element. For example, `ch := make(chan bool, 4)`, here we create a channel that can store 4 boolean elements. So in this channel, we are able to send 4 elements into it without blocking, but the goroutine will be blocked when you try to send a fifth element and no goroutine receives it. +Eu introduzi canais não-bufferizados acima. Go também tem canais em buffer que podem armazenar mais de um único elemento. Por exemplo, `ch: = make (chan bool, 4)`, aqui criamos um canal que pode armazenar 4 elementos booleanos. Assim, neste canal, podemos enviar 4 elementos sem bloqueio, mas a goroutine será bloqueada quando você tentar enviar um quinto elemento e nenhuma goroutine o receber. ch := make(chan type, n) n == 0 ! non-buffer(block) n > 0 ! buffer(non-block until n elements in the channel) -You can try the following code on your computer and change some values. +Você pode tentar o seguinte código no seu computador e alterar alguns valores. package main import "fmt" func main() { - c := make(chan int, 2) // change 2 to 1 will have runtime error, but 3 is fine + c := make(chan int, 2) // altera de 2 para 1 e retornará um erro, mas 3 funciona c <- 1 c <- 2 fmt.Println(<-c) fmt.Println(<-c) } -## Range and Close +## Alcance e fechamento(Range and Close) -We can use range to operate on buffer channels as in slice and map. +Podemos usar o range para operar em canais buffer como em slice e map. package main @@ -139,17 +139,17 @@ We can use range to operate on buffer channels as in slice and map. } } -`for i := range c` will not stop reading data from channel until the channel is closed. We use the keyword `close` to close the channel in above example. It's impossible to send or receive data on a closed channel; you can use `v, ok := <-ch` to test if a channel is closed. If `ok` returns false, it means the there is no data in that channel and it was closed. +`for i := range c` não parará de ler dados do canal até que o canal seja fechado. Usamos a palavra-chave `close` para fechar o canal no exemplo acima. É impossível enviar ou receber dados em um canal fechado; você pode usar `v, ok: = <-ch` para testar se um canal está fechado. Se `ok` retornar falso, significa que não há dados nesse canal e foi fechado. -Remember to always close channels in producers and not in consumers, or it's very easy to get into panic status. +Lembre-se sempre de fechar os canais nos produtores e não nos consumidores, ou é muito fácil entrar em status de pânico. -Another thing you need to remember is that channels are not like files. You don't have to close them frequently unless you are sure the channel is completely useless, or you want to exit range loops. +Outra coisa que você precisa lembrar é que os canais não são como arquivos. Você não precisa fechá-los com frequência, a menos que tenha certeza de que o canal é completamente inútil ou deseja sair de loops de intervalo. ## Select -In the above examples, we only use one channel, but how can we deal with more than one channel? Go has a keyword called `select` to listen to many channels. +Nos exemplos acima, usamos apenas um canal, mas como podemos lidar com mais de um canal? Go tem uma palavra-chave chamada `select` para ouvir muitos canais. -`select` is blocking by default and it continues to execute only when one of channels has data to send or receive. If several channels are ready to use at the same time, select chooses which to execute randomly. +`select` está bloqueando por padrão e continua a executar somente quando um dos canais tem dados para enviar ou receber. Se vários canais estiverem prontos para usar ao mesmo tempo, selecione a opção para executar aleatoriamente. package main @@ -180,18 +180,18 @@ In the above examples, we only use one channel, but how can we deal with more th fibonacci(c, quit) } -`select` has a `default` case as well, just like `switch`. When all the channels are not ready for use, it executes the default case (it doesn't wait for the channel anymore). +`select` tem um caso` default`, assim como `switch`. Quando todos os canais não estão prontos para uso, ele executa o caso padrão (ele não aguarda mais o canal). select { case i := <-c: // use i default: - // executes here when c is blocked + // Executa aqui quando C estiver bloqueado } ## Timeout -Sometimes a goroutine becomes blocked. How can we avoid this to prevent the whole program from blocking? It's simple, we can set a timeout in the select. +Às vezes uma goroutine fica bloqueada. Como podemos evitar isso para evitar que todo o programa bloqueie? É simples, podemos definir um tempo limite no select. func main() { c := make(chan int) @@ -213,30 +213,30 @@ Sometimes a goroutine becomes blocked. How can we avoid this to prevent the whol ## Runtime goroutine -The package `runtime` has some functions for dealing with goroutines. +O pacote `runtime` tem algumas funções para lidar com goroutines. -- `runtime.Goexit()` +- `runtime.Goexit ()` - Exits the current goroutine, but defered functions will be executed as usual. - -- `runtime.Gosched()` +Sai da gorout atual, mas as funções adiadas serão executadas como de costume. - Lets the scheduler execute other goroutines and comes back at some point. - -- `runtime.NumCPU() int` +- `runtime.Gosched ()` - Returns the number of CPU cores +Permite que o planejador execute outras goroutines e volte em algum momento. -- `runtime.NumGoroutine() int` +- `runtime.NumCPU () int` - Returns the number of goroutines +Retorna o número de núcleos da CPU -- `runtime.GOMAXPROCS(n int) int` +- `runtime.NumGoroutine () int` - Sets how many CPU cores you want to use +Retorna o número de goroutines + +- `runtime.GOMAXPROCS (n int) int` + +Define quantos núcleos de CPU você deseja usar ## Links -- [Directory](preface.md) -- Previous section: [interface](02.6.md) -- Next section: [Summary](02.8.md) +- [Prefácio](preface.md) +- Seção anterior: [interfaces](02.6.md) +- Próxima seção: [Summary](02.8.md)