Go-channel Practice 1

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

Some of the information from the old pool of resources, after some processing, and then into a new pool of resources, this process if the traditional way is to adopt a complete serial method of efficiency will be very low, the granularity is too coarse, the specific granularity can be refined to each unit of resources for granularity.

There is a resource pool that stores this person's information, takes each person out of it, then takes some processing and then saves it to the new resource pool, where the old and new resource pools are modeled with Oldarray and NewArray:

The code is as follows:


typePersonstruct{Namestring       Ageint       Addrstring}varOldpersonarray = [5]person{}varNewpersonarray = [5]person{}typePersonhandlerInterface{Batch(Origs <-Chanperson) <-ChanPersonHandle(Orig *person)}//struct implements the Personhandler interfacetypePersonhandlerimplstruct{}//Receive information from Origs and return to new channelfunc(HandlerPersonhandlerimpl)Batch(Origs <-Chanperson) <-Chanperson {dests: = Make(ChanPerson,  -)go func() { for{p, OK: = <-origsif!ok {Close(dests) Break                     } handler.Handle(&p) log.Printf("Old value:%v\n", P//time. Sleep (time. Second)                     Dests <-P}} ()returnDests}//Here to use reference deliveryfunc(HandlerPersonhandlerimpl)Handle(Orig *person) {orig.addr ="New Address"}funcGetpersonhandler() Personhandler {return&personhandlerimpl{}}//print The Oldpersonarray into the Chan<-personfuncFetchperson(OrigsChan<-person) { for_, V: =RangeOldpersonarray {fmt.Printf("Get the value:%v \ n", V) time.Sleep(Time.Second) Origs <-v}Close(Origs)}//fetch The value from the channel and store it into the NewpersonarrayfuncSaveperson(Dest <-Chanperson) <-Chanint{Intchann: = Make(Chanint)go func() {Index: =0               for{p, OK: = <-destif!ok { Break                     } time.Sleep(Time.Second) log.Printf("New value transfer%v \ n", p) Newpersonarray[index] = P index++} Intchann <-1       }()returnIntchann}funcInit() {//Use range if value is passed here, we're going to assign a value to Oldpersonarray.       Tmplen: =Len(Oldpersonarray) forI: =0; I < Tmplen; i++ {oldpersonarray[i].addr ="Old Address"              Oldpersonarray[i].age = i oldpersonarray[i].name = StrConv.Itoa(i)} log.Printf("First print init value:%v\n", Oldpersonarray)}funcMain() {Handeler: =Getpersonhandler() Origs: = Make(ChanPerson,  -) Dests: = Handeler.Batch(Origs)go func() {Fetchperson(Origs)} ()//Do not add go func words to wait until this sentence to execute the next sentence//Then the Orgis information is output completely shut down this time the statement from the Dest to receive information to start execution//So does not dynamically output this sentence plus go func will not be 1s dynamic output//If you put a fetchperson on the front, then the old value will not be output dynamically//fetchperson (origs)       Sign: =Saveperson(dests) log.Println(<-sign) log.Printf("Last print new value:%v \ n", Newpersonarray)}

  • A Personhandler interface is declared first, and a struct Personhandlerimpl is then declared to implement the two methods in the interface, and the INIT function is used for Oldarray initialization. Note that in order to reduce errors, the internal function is a one-way channel when the party declares.
  • Fetchperson from the Oldarray central data, and the data stored in the Origs channel, note that after the end of the data to the channel, the sender will close the channel, otherwise it may cause deadlock. Note in the main function, if the Fech operation is not put into a goroutine to execute, it is still serial, equivalent to the data are put into the channel, the other end to start fetching, did not play the advantages of concurrency.
  • The 3,4 batch function takes the person information out of the origs, processes it, uploads it to dests, and finally returns dests, noting that it is not all passed in before the dests is returned, but a new goroutine is started to perform the incoming operation. Return the dests at the same time, paying attention to actively closing the channel.
  • 5 Saveperson operation receives a <-chann after receiving the person information, writes the value to the new resource pool, and after the end of all writes, passes a sign channel to the main process and ends.
  • In summary, Goroutine is often used in conjunction with channel when it is necessary to dynamically output information. The most common usage is that a goroutine is responsible for writing data to the channel, then returning the channel, and extracting the information from other processes. For example, some of the previously written websocket receive information from the foreground, background processing information and then dynamically return to the foreground to play the results of the model, and this almost, in short, the specific asynchronous execution process to clarify, what channel, is responsible for the message is what.

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.