Goroutines It is difficult to write concurrency code, and it is more difficult to write code that accesses the network concurrently. The problem is that traditional threads do not scale well, and once the threads are running, it is difficult to control them. The Go Language project team began to solve the problem, and Goroutine was born. Essentially, Goroutines is a lightweight concurrency mechanism that interacts between threads by using a build called channels. They are very easy to use: Package main import ' FMT ' func Wait () { //wait around with a forever loop for { }} Func main () { go Wait ()} FMT. Println ("We didn ' t wait because it was called as a goroutine!")} In the above code, the Wait method is a dead loop, but we call it through go wait () rather than directly through wait (). This is to tell go that we want to invoke it in a goroutine way and run asynchronously at the same time. Since this loop is running in the background, running the program will not clog up because of a dead loop. So, go supports concurrency from the language itself. That is, there are concurrent primitives (Primitives)in the Go language. What is the point of this? It doesn't seem like a great move just because it's not a library or a module to implement concurrency. However, actually goroutine is fundamentally different from threads. The goroutine is lighter and more lightweight. Remember that in the server, we shouldn't create a thread for each client? However, with Goroutine, the situation is different: Package main import ( "FMT" "NET")//notice the arguments, the name of//the variable comes first and then COM Es the//type of the variable, just like in "Var"//declarationsfunc manageclient (conn net. Conn) { Conn. Write ([]byte ("hi!")) Conn. Close () //do something with the client} func main () { //we is creating a server she that listens //on Port 13 Notice that, similar to Ruby, //a method can has a return values (although //in Ruby, this would is an ARRA Y instead) listener, err: = Net. Listen ("TCP", ": 1337") for { //accept a connection connection, _: = Listener. Accept () go manageclient (Connection) }} Oh, wait a while! The code seems a little bit complicated, though the idea is simple. All right, let's take it one step at a time. |