Go Language Basics (vii) Concurrency and networking

Source: Internet
Author: User
Tags dnssec

1. Goroutine in this chapter will demonstrate the ability of Go to develop parallel programs using channel and Goroutine. Goroutine is the core element of Go concurrency capability. But what exactly is Goroutine? called Goroutine because the existing phrases-thread, progression, process, and so on-pass inaccurate meanings. Goroutine has a simple model: it is a function that executes in parallel with other goroutine and has the same address space. It is lightweight and only a little bit more than allocating stack space. The initial stack is very small, so they are also inexpensive, and are allocated (and freed) on the heap space as needed.  goroutine is a normal function, just need to use the reserved word go as the beginning. Ready ("Tea", 2) ← Normal function call Go ready ("Tea", 2) ←ready () as Goroutine run  go routine practice func Ready (W string, sec int) {Time . Sleep (time. Duration (SEC) * time. Second) fmt. Println (W, "is ready!")} Func main () {Go Ready ("Tea", 2) Go Ready ("Coffee", 1) fmt. Println ("I ' m Waiting") time. Sleep (5 * time. Second)} output: I ' m waiting← immediately coffee is ready! ← Tea is ready! after 1 seconds ← After 2 seconds  2, use the channel if you do not wait for Goroutine to execute (for example, remove the I ' m waiting line), the program terminates immediately, and any goroutine being executed will stop. In order to fix this, we need some mechanism that can communicate with Goroutine. This mechanism is used in the form of channels. The channel can be analogous to a bidirectional pipeline in Unix SEHLL: It can send or receive values through it. These values can only be of a specific type: Channel type. When defining a channel, you also need to define the type of value sent to the channel. Note that you must use make to create channel:ci: = made (chan int) cs: = Made (Chan string) CF: = Made (chan interface{}) Create channel CI for sending and receiving integers, creating channel CS for strings, and channel CF using an empty interface to satisfy various types. Sending or receiving data to the channel is done by a similar operator: <-. The specific action depends on the position of the operator: CI <-1← sends an integer 1 to channelci<-ci← receive integer from Channel ci i: = <-ci← Receive integers from channel CI and save to I   put these in the instance:  //defines C as the channel of the int type. That means: This channel transmits integers. Note that this variable is global so that goroutine can access it; var c chan IntFunc Ready (W string, sec int) {time. Sleep (time. Duration (SEC) * time. Second) fmt. Println (W, "is ready!") C <-1//Send integer 1 to channel C;} Func Main () {c = make (chan int)//Initialize CGO Ready ("Tea", 2)//Use the reserved word go to start a goroutinego ("Coffee", 1) fmt. Println ("I ' m waiting, but not too long") <-c//waits until a value is received from the channel. Note that the received value is discarded; <-c//Two goroutines, receive two values. }  What if I don't know how many goroutine have started? Here's another Go built-in reserved word: SELECT. The data entered on the channel can be monitored by select (and other things).   Using Select in this program does not make it shorter because there are too few goroutine running. Remove the two lines of <-c and replace them with the following: Using Selectl:for {Select {case <-c:i++if i > 1 {break L}}} will now wait forever. The Loop L is exited only if multiple responses are received from channel C. &NBSP;3, parallel operation although Goroutine is concurrently executed, but they are not run in parallel. If you don't tell Go extras, only one goroutine will be executed at the same time. Use runtime. Gomaxprocs (n) can set the number of Goroutine parallel executions.  gomaxprocs sets the maximum number of CPUs that are running concurrently and returns the previous settings. If n < 1, the current setting is not changed. When the schedule is improved, this is removed.   When you create a chennel with ch: = Make (chan bool) in Go, the bool-type unbuffered channel is created. What does this mean for the program? First, if Read (value: = <-ch) It will be blocked until data is received. Second, any send (ch<-5) will be blocked until the data is read out. Unbuffered Channel is a great tool for synchronizing between multiple goroutine. But Go also allows you to specify the buffer size of the channel, which is simply how many elements the channel can store. CH: = Make (chan bool, 4), creating a bool-type channel that can store 4 elements. In this channel, the first 4 elements can be written without blocking. When the 5th element is written, the code blocks until the other goroutine reads some elements from the channel, freeing up space.   4, close the channel when the channel is closed, the reader needs to know about it. The following code shows how to check if the channel is being related. X, OK = <-ch When OK is assigned true means that the channel has not been closed and the data can be read. Otherwise OK is assigned to false. In this case, the channel is closed.    17, communication Understanding files, directories, network communications and running other programs. The I/O core of Go is interface io. Reader and IO. Writer. In Go, it is very easy to read from a file (or write), that is, to use the OS package  1, read from a file (unbuffered) packages mainimport "OS" func Main () {buf: = make ([]byte, 1024x768) f,_: = OS. Open ("/etc/passwd")//opening file, OS. Open returns an IO implementation. Readerand IO. Writer's *os. File;defer f.close ()//Make sure to close the f;for {n,_: = F.read (BUF)//Read 1024 bytes at a time if n==0 {break}//arrive at the end of the file OS. Stdout.write (Buf[:n])//writes the content to the OS. Stdout}}  2, read from file (buffer, with Bufio Pack) package Mainimport ("OS"; "Bufio") func main () {buf: = make ([]byte, 1024x768) f,_: = OS. Open ("/etc/passwd")//Opening file defer f.close ()//convert F to buffered Reader. Newreader requires an IO. reader,//so maybe you think it's going to go wrong. But not really. Any of the Read () functions implement this interface. At the same time, from the above example can be seen, *os. File has done so; r: = Bufio. Newreader (f) W: = Bufio. Newwriter (OS. Stdout) defer W.flush () for {n, _: = R.read (BUF)//read from reader, write to writer, and then output the file to the screen. if n = = 0 {break}w.write (Buf[0:n])}} 3, Io. The Readerio.reader interface is important for the Go language. Many (if not all) functions need to pass IO. Reader reads some data as input  4, one line reads the file f,_: = OS. Open ("/etc/passwd");d efer F.close () r: = Bufio. Newreader (f) ← Make it a bufio in order to access the ReadString method S, OK: = r.readstring (' \ n ') {← read one line from input//... |←s saved the string, which can be parsed by a string packet It |  5, command-line arguments a DNS query tool://defines the bool identifier,-dnssec. The variable must be a pointer, or the package cannot set its value dnssec: = Flag. Bool ("Dnssec", False, "ReqUestdnssecrecords ") Port: = Flag. String ("Port", "N", "Set the Query Port")//similar, port option; flag. Usage = func () {//Simple redefine usage function FMT. fprintf (OS. Stderr, "Usage:%s [OPTIONS] [name ...] \ n ", Os. Args[0]) flag. Printdefaults ()//each identity specified, Printdefaults will output the Help information;} Flag. Parse ()//parse the identity and populate the variable. When parameters are parsed, they can be used: if *dnssec {← Define incoming parameters dnssec//do point} 6, execute commands os/exec package has functions to execute external commands, which is also the main way to execute commands in Go. By defining a *exec with a number of methods. CMD structure to use. Execute Ls-l:import "os/exec" cmd: = exec. Command ("/bin/ls", "-L") Err: = cmd. Run () The example above runs "ls-l" but does not handle any of the data it returns   obtains information from the command line's standard output by: import "exec" cmd: = exec. Command ("/bin/ls", "-l") buf, err: = cmd. Output () ←buf is a []byte  7, network-related type and function that can be found in the net package. The most important of these functions is Dial. When Dial to a remote system, this function returns the Conn interface type, which can be used to send or receive information. The function Dial Concise abstraction of the network layer and the Transport layer. So IPv4 or ipv6,tcp or UDP can share an interface.   connects to the remote system via TCP (port 80), then UDP, and finally TCP via IPV6, roughly like this: Conn, E: = Dial ("TCP", "192.0.32.10:80") conn, E: = Dial ("UDP", "192.0.32.10:80") conn, E: = Dial ("TCP", "[2620:0:2d0:200::10]:80") ← square brackets are mandatoryIf there is no error (returned by e), you can use Conn to read and write from the socket. The original definition in package NET is://Read reads data from the connection. Read (b []byte) (n int, err error) This makes conn an IO. Reader. Write writes data to the connection. Write (b []byte) (n int, err error) This also makes Conn an IO. Writer, in fact Conn is IO. Readwriter. But these are implied by the lower level   usually should always use higher levels of packages: HTTP A simple HTTP Get example of package Mainimport ("Io/ioutil"; Net/http ";" FMT ")//Required import func main () {r,err: = http. Get ("Http://www.google.com/robots.txt")//Use HTTP. Get gets htmlif err! = Nil {fmt. Printf ("%s\n", err. String ()); return}//error handling B, err: = Ioutil. ReadAll (R.body)//reads the entire content into Br. Body.close () If Err = = Nil {fmt. Printf ("%s", string (b))}//If everything OK, print content}

Go Language Basics (vii) Concurrency and networking

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.