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: en/02.7.md
+21-21
Original file line number
Diff line number
Diff line change
@@ -1,15 +1,15 @@
1
1
# Concurrency
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
+
It is said that Go is the C of the 21st century. I think there are two reasons for it. 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.
4
4
5
5
## goroutine
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.
6
+
7
+
goroutines and concurrency are built into the core design of Go. They're similar to threads but work differently. 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.
8
8
9
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*** ).
10
10
```Go
11
11
gohello(a, b, c)
12
-
```
12
+
```
13
13
Let's see an example.
14
14
```Go
15
15
package main
@@ -43,28 +43,28 @@ Output:
43
43
hello
44
44
world
45
45
hello
46
-
```
46
+
```
47
47
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.
48
48
49
49
runtime.Gosched() means let the CPU execute other goroutines, and come back at some point.
50
50
51
51
In Go 1.5,the runtime now sets the default number of threads to run simultaneously, defined by GOMAXPROCS, to the number of cores available on the CPU.
52
52
53
-
Before Go 1.5,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.
53
+
Before Go 1.5,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.
54
54
55
55
## channels
56
56
57
-
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`.
57
+
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`. A `channel` is like 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`.
58
58
```Go
59
59
ci:=make(chanint)
60
60
cs:=make(chanstring)
61
61
cf:=make(chaninterface{})
62
-
```
62
+
```
63
63
channel uses the operator `<-` to send or receive data.
64
64
```Go
65
65
ch <- v // send v to channel ch.
66
66
v:=<-ch // receive data from ch, and assign to v
67
-
```
67
+
```
68
68
Let's see more examples.
69
69
```Go
70
70
package main
@@ -90,8 +90,8 @@ func main() {
90
90
fmt.Println(x, y, x+y)
91
91
}
92
92
93
-
```
94
-
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.
93
+
```
94
+
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.
95
95
96
96
## Buffered channels
97
97
@@ -101,9 +101,9 @@ ch := make(chan type, n)
101
101
102
102
n == 0 ! non-buffer(block)
103
103
n > 0 ! buffer(non-block until n elements in the channel)
104
-
```
104
+
```
105
105
You can try the following code on your computer and change some values.
106
-
```Go
106
+
```Go
107
107
package main
108
108
109
109
import"fmt"
@@ -116,7 +116,7 @@ func main() {
116
116
fmt.Println(<-c)
117
117
}
118
118
119
-
```
119
+
```
120
120
## Range and Close
121
121
122
122
We can use range to operate on buffer channels as in slice and map.
@@ -144,12 +144,12 @@ func main() {
144
144
}
145
145
}
146
146
147
-
```
147
+
```
148
148
`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.
149
149
150
150
Remember to always close channels in producers and not in consumers, or it's very easy to get into panic status.
151
151
152
-
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.
152
+
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.
153
153
154
154
## Select
155
155
@@ -186,7 +186,7 @@ func main() {
186
186
fibonacci(c, quit)
187
187
}
188
188
189
-
```
189
+
```
190
190
`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).
191
191
```Go
192
192
select {
@@ -195,7 +195,7 @@ case i := <-c:
195
195
default:
196
196
// executes here when c is blocked
197
197
}
198
-
```
198
+
```
199
199
## Timeout
200
200
201
201
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.
@@ -218,19 +218,19 @@ func main() {
218
218
<-o
219
219
}
220
220
221
-
```
221
+
```
222
222
## Runtime goroutine
223
223
224
224
The package `runtime` has some functions for dealing with goroutines.
225
225
226
226
-`runtime.Goexit()`
227
227
228
228
Exits the current goroutine, but defered functions will be executed as usual.
229
-
229
+
230
230
-`runtime.Gosched()`
231
231
232
232
Lets the scheduler execute other goroutines and comes back at some point.
Copy file name to clipboardExpand all lines: en/03.1.md
+9-9
Original file line number
Diff line number
Diff line change
@@ -2,7 +2,7 @@
2
2
3
3
Every time you open your browsers, type some URLs and press enter, you will see beautiful web pages appear on your screen. But do you know what is happening behind these simple actions?
4
4
5
-
Normally, your browser is a client. After you type a URL, it takes the host part of the URL and sends it to a DNS server in order to get the IP address of the host. Then it connects to the IP address and asks to setup a TCP connection. The browser sends HTTP requests through the connection. The server handles them and replies with HTTP responses containing the content that make up the web page. Finally, the browser renders the body of the web page and disconnects from the server.
5
+
Normally, your browser is a client. After you type a URL, it takes the host part of the URL and sends it to a Domain Name Server (DNS) in order to get the IP address of the host. Then it connects to the IP address and asks to setup a TCP connection. The browser sends HTTP requests through the connection. The server handles them and replies with HTTP responses containing the content that make up the web page. Finally, the browser renders the body of the web page and disconnects from the server.
6
6
7
7

8
8
@@ -28,13 +28,13 @@ The full name of a URL is Uniform Resource Locator. It's for describing resource
scheme assign underlying protocol (such as HTTP, HTTPS, FTP)
30
30
host IP or domain name of HTTP server
31
-
port# default port is 80, and it can be omitted in this case.
31
+
port# default port is 80, and it can be omitted in this case.
32
32
If you want to use other ports, you must specify which port. For example,
33
33
http://www.cnblogs.com:8080/
34
34
path resources path
35
35
query-string data are sent to server
36
36
anchor anchor
37
-
37
+
38
38
DNS is an abbreviation of Domain Name System. It's the naming system for computer network services, and it converts domain names to actual IP addresses, just like a translator.
39
39
40
40

@@ -47,7 +47,7 @@ To understand more about its working principle, let's see the detailed DNS resol
47
47
2. If no mapping relationships exist in the hosts' files, the operating system will check if any cache exists in the DNS. If so, then the domain name resolution is complete.
48
48
3. If no mapping relationships exist in both the host and DNS cache, the operating system finds the first DNS resolution server in your TCP/IP settings, which is likely your local DNS server. When the local DNS server receives the query, if the domain name that you want to query is contained within the local configuration of its regional resources, it returns the results to the client. This DNS resolution is authoritative.
49
49
4. If the local DNS server doesn't contain the domain name but a mapping relationship exists in the cache, the local DNS server gives back this result to the client. This DNS resolution is not authoritative.
50
-
5. If the local DNS server cannot resolve this domain name either by configuration of regional resources or cache, it will proceed to the next step, which depends on the local DNS server's settings.
50
+
5. If the local DNS server cannot resolve this domain name either by configuration of regional resources or cache, it will proceed to the next step, which depends on the local DNS server's settings.
51
51
-If the local DNS server doesn't enable forwarding, it routes the request to the root DNS server, then returns the IP address of a top level DNS server which may know the domain name, `.com` in this case. If the first top level DNS server doesn't recognize the domain name, it again reroutes the request to the next top level DNS server until it reaches one that recognizes the domain name. Then the top level DNS server asks this next level DNS server for the IP address corresponding to `www.qq.com`.
52
52
-If the local DNS server has forwarding enabled, it sends the request to an upper level DNS server. If the upper level DNS server also doesn't recognize the domain name, then the request keeps getting rerouted to higher levels until it finally reaches a DNS server which recognizes the domain name.
53
53
@@ -65,15 +65,15 @@ Now we know clients get IP addresses in the end, so the browsers are communicati
65
65
66
66
The HTTP protocol is a core part of web services. It's important to know what the HTTP protocol is before you understand how the web works.
67
67
68
-
HTTP is the protocol that is used to facilitate communication between browsers and web servers. It is based on the TCP protocol and usually uses port 80 on the side of the web server. It is a protocol that utilizes the request-response model -clients send requests and servers respond. According to the HTTP protocol, clients always setup new connections and send HTTP requests to servers. Servers are not able to connect to clients proactively, or establish callback connections. The connection between a client and a server can be closed by either side. For example, you can cancel your download request and HTTP connection and your browser will disconnect from the server before you finish downloading.
68
+
HTTP is the protocol that is used to facilitate communication between browser and web server. It is based on the TCP protocol and usually uses port 80 on the side of the web server. It is a protocol that utilizes the request-response model -clients send requests and servers respond. According to the HTTP protocol, clients always setup new connections and send HTTP requests to servers. Servers are not able to connect to clients proactively, or establish callback connections. The connection between a client and a server can be closed by either side. For example, you can cancel your download request and HTTP connection and your browser will disconnect from the server before you finish downloading.
69
69
70
70
The HTTP protocol is stateless, which means the server has no idea about the relationship between the two connections even though they are both from same client. To solve this problem, web applications use cookies to maintain the state of connections.
71
71
72
72
Because the HTTP protocol is based on the TCP protocol, all TCP attacks will affect HTTP communications in your server. Examples of such attacks are SYN flooding, DoS and DDoS attacks.
73
73
74
74
### HTTP request package (browser information)
75
75
76
-
Request packages all have three parts: request line, request header, and body. There is one blank line between header and body.
76
+
Request packages all have three parts: request line, request header, and body. There is one blank line between header and body.
77
77
78
78
GET /domains/example/ HTTP/1.1 // request line: request method, URL, protocol and its version
79
79
Host:www.iana.org // domain name
@@ -107,7 +107,7 @@ Let's see what information is contained in the response packages.
107
107
Date:Date: Tue, 30 Oct 2012 04:14:25 GMT // responded time
108
108
Content-Type: text/html // responded data type
109
109
Transfer-Encoding: chunked // it means data were sent in fragments
110
-
Connection: keep-alive // keep connection
110
+
Connection: keep-alive // keep connection
111
111
Content-Length: 90 // length of body
112
112
// blank line
113
113
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"... // message body
@@ -122,7 +122,7 @@ The status code informs the client of the status of the HTTP server's response.
122
122
- 4xx Client Error
123
123
- 5xx Server Error
124
124
125
-
Let's see more examples about response packages. 200 means server responded correctly, 302 means redirection.
125
+
Let's see more examples about response packages. 200 means server responded correctly, 302 means redirection.
126
126
127
127

128
128
@@ -134,7 +134,7 @@ The term stateless doesn't mean that the server has no ability to keep a connect
134
134
135
135
In HTTP/1.1, Keep-alive is used by default. If clients have additional requests, they will use the same connection for them.
136
136
137
-
Notice that Keep-alive cannot maintain one connection forever; the application running in the server determines the limit with which to keep the connection alive for, and in most cases you can configure this limit.
137
+
Notice that Keep-alive cannot maintain one connection forever; the application running in the server determines the limit with which to keep the connection alive for, and in most cases you can configure this limit.
0 commit comments