Skip to content

Commit 7ef80e8

Browse files
Tradução ddas Concorrencias
tradução da páginas de concorrencias em Go
1 parent a0f589e commit 7ef80e8

File tree

1 file changed

+48
-48
lines changed

1 file changed

+48
-48
lines changed

pt-br/02.7.md

+48-48
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
# Concurrency
1+
# Concorrência
22

3-
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.
3+
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.
44

55
## goroutine
66

7-
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.
7+
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.
88

9-
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*** ).
9+
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 ***).
1010

1111
go hello(a, b, c)
1212

13-
Let's see an example.
13+
Vamos ao exemplo:
1414

1515
package main
1616

@@ -31,7 +31,7 @@ Let's see an example.
3131
say("hello") // current goroutine
3232
}
3333

34-
Output:
34+
Retorno
3535

3636
hello
3737
world
@@ -43,26 +43,26 @@ Output:
4343
world
4444
hello
4545

46-
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.
46+
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.
4747

48-
runtime.Gosched() means let the CPU execute other goroutines, and come back at some point.
48+
runtime.Gosched () significa deixar a CPU executar outras goroutines e voltar em algum momento.
4949

50-
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).
50+
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).
5151

52-
## channels
52+
## Canais(Channels)
5353

54-
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`.
54+
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`.
5555

5656
ci := make(chan int)
5757
cs := make(chan string)
5858
cf := make(chan interface{})
5959

60-
channel uses the operator `<-` to send or receive data.
60+
canais usa, o operador `<-` para enviar ou receber dados.
6161

62-
ch <- v // send v to channel ch.
63-
v := <-ch // receive data from ch, and assign to v
62+
ch <- v // envia v para o canal ch.
63+
v := <-ch // recebe dados de ch, e os assina em v
6464

65-
Let's see more examples.
65+
Exemplos:
6666

6767
package main
6868

@@ -73,7 +73,7 @@ Let's see more examples.
7373
for _, v := range a {
7474
total += v
7575
}
76-
c <- total // send total to c
76+
c <- total // envia o total para c
7777
}
7878

7979
func main() {
@@ -82,39 +82,39 @@ Let's see more examples.
8282
c := make(chan int)
8383
go sum(a[:len(a)/2], c)
8484
go sum(a[len(a)/2:], c)
85-
x, y := <-c, <-c // receive from c
85+
x, y := <-c, <-c // recebe de c
8686

8787
fmt.Println(x, y, x + y)
8888
}
8989

90-
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.
90+
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.
9191

92-
## Buffered channels
92+
## Canais em Buffer
9393

94-
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.
94+
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.
9595

9696
ch := make(chan type, n)
9797

9898
n == 0 ! non-buffer(block)
9999
n > 0 ! buffer(non-block until n elements in the channel)
100100

101-
You can try the following code on your computer and change some values.
101+
Você pode tentar o seguinte código no seu computador e alterar alguns valores.
102102

103103
package main
104104

105105
import "fmt"
106106

107107
func main() {
108-
c := make(chan int, 2) // change 2 to 1 will have runtime error, but 3 is fine
108+
c := make(chan int, 2) // altera de 2 para 1 e retornará um erro, mas 3 funciona
109109
c <- 1
110110
c <- 2
111111
fmt.Println(<-c)
112112
fmt.Println(<-c)
113113
}
114114

115-
## Range and Close
115+
## Alcance e fechamento(Range and Close)
116116

117-
We can use range to operate on buffer channels as in slice and map.
117+
Podemos usar o range para operar em canais buffer como em slice e map.
118118

119119
package main
120120

@@ -139,17 +139,17 @@ We can use range to operate on buffer channels as in slice and map.
139139
}
140140
}
141141

142-
`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.
142+
`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.
143143

144-
Remember to always close channels in producers and not in consumers, or it's very easy to get into panic status.
144+
Lembre-se sempre de fechar os canais nos produtores e não nos consumidores, ou é muito fácil entrar em status de pânico.
145145

146-
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.
146+
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.
147147

148148
## Select
149149

150-
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.
150+
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.
151151

152-
`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.
152+
`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.
153153

154154
package main
155155

@@ -180,18 +180,18 @@ In the above examples, we only use one channel, but how can we deal with more th
180180
fibonacci(c, quit)
181181
}
182182

183-
`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).
183+
`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).
184184

185185
select {
186186
case i := <-c:
187187
// use i
188188
default:
189-
// executes here when c is blocked
189+
// Executa aqui quando C estiver bloqueado
190190
}
191191

192192
## Timeout
193193

194-
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.
194+
À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.
195195

196196
func main() {
197197
c := make(chan int)
@@ -213,30 +213,30 @@ Sometimes a goroutine becomes blocked. How can we avoid this to prevent the whol
213213

214214
## Runtime goroutine
215215

216-
The package `runtime` has some functions for dealing with goroutines.
216+
O pacote `runtime` tem algumas funções para lidar com goroutines.
217217

218-
- `runtime.Goexit()`
218+
- `runtime.Goexit ()`
219219

220-
Exits the current goroutine, but defered functions will be executed as usual.
221-
222-
- `runtime.Gosched()`
220+
Sai da gorout atual, mas as funções adiadas serão executadas como de costume.
223221

224-
Lets the scheduler execute other goroutines and comes back at some point.
225-
226-
- `runtime.NumCPU() int`
222+
- `runtime.Gosched ()`
223+
224+
Permite que o planejador execute outras goroutines e volte em algum momento.
225+
226+
- `runtime.NumCPU () int`
227227

228-
Returns the number of CPU cores
228+
Retorna o número de núcleos da CPU
229229

230-
- `runtime.NumGoroutine() int`
230+
- `runtime.NumGoroutine () int`
231231

232-
Returns the number of goroutines
232+
Retorna o número de goroutines
233233

234-
- `runtime.GOMAXPROCS(n int) int`
234+
- `runtime.GOMAXPROCS (n int) int`
235235

236-
Sets how many CPU cores you want to use
236+
Define quantos núcleos de CPU você deseja usar
237237

238238
## Links
239239

240-
- [Directory](preface.md)
241-
- Previous section: [interface](02.6.md)
242-
- Next section: [Summary](02.8.md)
240+
- [Prefácio](preface.md)
241+
- Seção anterior: [interfaces](02.6.md)
242+
- Próxima seção: [Summary](02.8.md)

0 commit comments

Comments
 (0)