Go Example Tour (next)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Introduce

This is from go by example example, spent a few days to write these examples, feel very helpful to me, for beginners, my advice is to look at this go to the book from beginning to end, and then look at these examples, each of the examples are hand-knocking, for your help is still very big. In the process of knocking these examples, there are some questions, there are some knowledge of the expansion, so summed up this article.

Time and Channel

The Golang time package features a timer, while the timer and channel are perfectly fused, creating a timer that returns a channel, which is blocked by reading the channel before the timer expires. The channel will become readable until the time is reached.

Func Main () {//Creates a timer,2The event is sent to timer1 in seconds. CChannel Timer1: = Time. Newtimer(Time. Second*2)//Wait timer expires data: = <-timer1. CThe data received .- -- -  the: -:19.337701998+0800CST FMT. Println("Timer 1 Expired") FMT. Println("Timer 1 Expired", data) Timer2: = Time. Newtimer(Time. Second) go func () {<-timer2. CFmt. Println("Timer 2 Expired")} ()//Turn off timer stop2: = Timer2. Stop() if STOP2 {FMT. Println("Timer 2 Stopped")    }}

In addition to the timer function, the time package also has a ticker,ticker that is also a perfect fusion of the channel, creating a ticker that will return to the channel
Through range this channel. To indicate the arrival of each interval. Combined with go, it is easy to implement the function of a timed task.

func main() {    //创建了定时器,每time.Millisecond500就产生事件,发送到chnanel    ticker := time.NewTicker(time.Millisecond500)    go func() {        for t := range ticker.C {            fmt.Println("Tick at",t)        }    }()    //睡上一段事件,然后关闭    time.Sleep(time.Millisecond1600)    ticker.Stop()    fmt.Println("Ticker stopped")}

Goroutines and Work Pool

Goroutines Combine channel it is easy to implement a work pool, open n goroutines, and then this n goroutines together to read the channel, read the channel
To do the work, and then the result is passed through another channel, the model is simple. It's still easy to implement with go.

funcWorker (IDint, Jobs <-Chan int, resultChan<-int) { forJ: =RangeJobs {FMT. Println ("Worker"Id"Processing Job", j) time. Sleep (time. Second) Result <-J *2}}funcMain () {jobs: = Make(Chan int, the) Results: = Make(Chan int, the)//Start three worker     forW: =1; W <=3; w++ {GoWorker (W,jobs,results)}//Cycle 9 times, send tasks     forJ: =1; J <=9; J + + {jobs <-J}Close(jobs)//loop to get results     forA: =1; A <=9; a++ {<-results}}

Rate limiting and channel

Speed limit This is a mechanism for controlling resource utilization and guaranteeing quality of service, and Golang supports it gracefully through Goroutines,channel and tickers. For example, to handle the speed limit of Web requests, each request will be read a tick first, this tick is readable every fixed time, so that the speed limit can be achieved.

func  Main () {requests: = make  (chan  int     ,5 )    //send five messages  for  I: = 1 ; I <= 5 ; i++ {requests <-i} close  ( Requests) //created the timer, then traversed the channel, printing the message  limiter: = time. Tick (time. Millisecond * ) for  req: = range  requests {<-limiter //every time. Millisecond * 200, plays the role of speed limit  FMT. Println ( "Requests" , Req,time. Now ())}}  

However, there is a problem with the speed limit, that is, the concurrency number is only 1, if you can have a fixed number of concurrent cases of the low speed?, which requires the use of the channel buffer function. The time above. The channel returned by tick is not buffer, so only one request can be processed at a time, if the channel is buffer, such as the size of the buffer is n then can concurrently receive n requests, want to process the n+ 1 requests are required to wait for a fixed time.

funcMain () {//created another time. Time-Similar channelBurstylimiter: = Make(ChanTime. Time, 3)//Send three     forI: =0; I <3; i++ {burstylimiter <-time. Now ()}Go func() { forT: =RangeTime. Tick (Time.millisecond * $) {Burstylimiter <-t//per $ * Time.millisecond Send an event to Burstylimiter}} () Burstyrequests: = Make(Chan int, 5) forI: =1; I <=5; i++ {burstyrequests <-i//Send five data}Close(burstyrequests) forReq: =Rangeburstyrequests {//Start speed limit read now<-burstylimiter//In the first three to read the time is not blocked, until the fourth time to read the beginning of the limiter speed limitFmt. Println ("Request", Req,time. Now ())}}

customizing Sort and interface

Golang's sort package comes with a sorting feature, but if you want to sort the data structure that the user has defined, it's not half right, requiring the user to overload the relational operator in C + + needs to be perfectly fused with interface in Golang, as long as the user implements Len, Less,swap three interfaces, it's that simple.

 PackageMainImport "FMT"Import "Sort"//string Slice Alias, add a method to this alias structtypeBylength []stringfunc(S Bylength) Len ()int{return Len(s)}func(S Bylength) Swap (i,jint) {S[i],s[j] = s[j],s[i]}func(S Bylength) Less (i,jint)BOOL{return Len(S[i]) <Len(S[j])}the//sort interface needs to implement Swap less and LenfuncMain () {fruits: = []string{"Peach","Banana","Kiwi"} sort. Sort (bylength (fruits)) fmt. Println (Fruits)}

Signal and Channel

Golang once again combines the signals and channel on UNIX, and on Unix, by giving signal registration processing functions to complete signal processing, in Golang, by associating the signal with the channel, when a signal arrives the channel is readable. The returned result is the number of the signal.

Import "FMT"Import "OS"Import "Os/signal"Import "Syscall"funcMain () {//os. Signal type of CHNSIGs: = Make(ChanOs. Signal, 1) Done: = Make(Chan BOOL, 1)//through norify to register the signal,Signal. Notify (Sigs,syscall. Sigint,syscall. SIGTERM)//Combine SIGINT and sigterm with SIGs channel.    //co-formed to collect signals and then send done Chan to indicate completion    Go func() {sig: = <-sigs FMT. Println () fmt. Println (SIG) Done <-true} () Fmt. Println ("Awaiting signal") <-done FMT. Println ("Exiting")}
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.