You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: pt-br/02.7.md
+48-48
Original file line number
Diff line number
Diff line change
@@ -1,16 +1,16 @@
1
-
# Concurrency
1
+
# Concorrência
2
2
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.
4
4
5
5
## goroutine
6
6
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.
8
8
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***).
10
10
11
11
go hello(a, b, c)
12
12
13
-
Let's see an example.
13
+
Vamos ao exemplo:
14
14
15
15
package main
16
16
@@ -31,7 +31,7 @@ Let's see an example.
31
31
say("hello") // current goroutine
32
32
}
33
33
34
-
Output:
34
+
Retorno
35
35
36
36
hello
37
37
world
@@ -43,26 +43,26 @@ Output:
43
43
world
44
44
hello
45
45
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.
47
47
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.
49
49
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).
51
51
52
-
## channels
52
+
## Canais(Channels)
53
53
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`.
55
55
56
56
ci := make(chan int)
57
57
cs := make(chan string)
58
58
cf := make(chan interface{})
59
59
60
-
channel uses the operator`<-`to send or receive data.
60
+
canais usa, o operador`<-`para enviar ou receber dados.
61
61
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
64
64
65
-
Let's see more examples.
65
+
Exemplos:
66
66
67
67
package main
68
68
@@ -73,7 +73,7 @@ Let's see more examples.
73
73
for _, v := range a {
74
74
total += v
75
75
}
76
-
c <- total // send total to c
76
+
c <- total // envia o total para c
77
77
}
78
78
79
79
func main() {
@@ -82,39 +82,39 @@ Let's see more examples.
82
82
c := make(chan int)
83
83
go sum(a[:len(a)/2], c)
84
84
go sum(a[len(a)/2:], c)
85
-
x, y := <-c, <-c // receive from c
85
+
x, y := <-c, <-c // recebe de c
86
86
87
87
fmt.Println(x, y, x + y)
88
88
}
89
89
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.
91
91
92
-
## Buffered channels
92
+
## Canais em Buffer
93
93
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.
95
95
96
96
ch := make(chan type, n)
97
97
98
98
n == 0 ! non-buffer(block)
99
99
n > 0 ! buffer(non-block until n elements in the channel)
100
100
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.
102
102
103
103
package main
104
104
105
105
import "fmt"
106
106
107
107
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
109
109
c <- 1
110
110
c <- 2
111
111
fmt.Println(<-c)
112
112
fmt.Println(<-c)
113
113
}
114
114
115
-
## Range and Close
115
+
## Alcance e fechamento(Range and Close)
116
116
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.
118
118
119
119
package main
120
120
@@ -139,17 +139,17 @@ We can use range to operate on buffer channels as in slice and map.
139
139
}
140
140
}
141
141
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.
143
143
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.
145
145
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.
147
147
148
148
## Select
149
149
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.
151
151
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.
153
153
154
154
package main
155
155
@@ -180,18 +180,18 @@ In the above examples, we only use one channel, but how can we deal with more th
180
180
fibonacci(c, quit)
181
181
}
182
182
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).
184
184
185
185
select {
186
186
case i := <-c:
187
187
// use i
188
188
default:
189
-
// executes here when c is blocked
189
+
// Executa aqui quando C estiver bloqueado
190
190
}
191
191
192
192
## Timeout
193
193
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.
195
195
196
196
func main() {
197
197
c := make(chan int)
@@ -213,30 +213,30 @@ Sometimes a goroutine becomes blocked. How can we avoid this to prevent the whol
213
213
214
214
## Runtime goroutine
215
215
216
-
The package`runtime`has some functions for dealing with goroutines.
216
+
O pacote`runtime`tem algumas funções para lidar com goroutines.
217
217
218
-
-`runtime.Goexit()`
218
+
-`runtime.Goexit()`
219
219
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.
223
221
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.
0 commit comments