[Go] is formed by using external communication channel circulation duct

To solve this problem, if there is such a large circulation, taken from a large file to be logical processing, then the logic of the code to be placed in each line of the loop inside the loop, so there may be a for loop nested logic, layer after layer, similar to the Russian dolls. If you put out you will need to save each line of a cycle of data into an array or slice it, this will represent a significant memory

Then you can use this technique to adequately address the nesting cycle, but also occupy large memory data solutions do not exist

Create a channel, open a goroutine, conducted for looping through the groutine inside, each row of data is sent to the channel in
the main groutine inside, read channel, because the receiver is always performed first than the sender, then this place will that a data block waiting for the arrival of
so that the formation of such a benign synchronous operation, although it is performed in different groutine inside, but always executed synchronously, and solve the problem of nested loop

Package main 

Import " FMT " 

Import " Time " 

FUNC main () { 
    ARR: = [] int { . 1 , 2 , . 3 , . 4 , . 5 , . 6 } 
    Yields: = the make (Chan int ) 
    Go FUNC () { 
        for _, I: = Range ARR {
             // each prints here, the outer loop then jump 
            FMT .Println ( " circulated " , I) 
            Yields <- I
            // This is the effect of preventing the execution of fast see 
            Time .sleep ( Time .Second) 
        } 
        Close (Yields) 
    } () 
    for I: = Range Yields {
         FMT .Println ( " outer loop: " , I) 
    } 
}

This effect is

Circulating an 
outer loop: an 
inner loop 2 
outer loop: 2 
within the cycle 3 
the outer loop: 3 
inner loop 4 
outer loop: 4 
inner loop 5 
outer loop: 5 
inner loop 6 
outer loop: 6

If that channel is a channel have the cache, the cache will first of all into the channel number, just outside the loop execution, this has in many cases in

Yields: = the make (Chan int , 6 ) 
inner loop 1 
inside loop 2 
within the loop 3 
circulating 4 
inner loop 5 
inner loop 6 
outer loop: an 
outer loop: 2 
outer loop: 3 
outer loop: 4 
outer loop: 5 
cycles outer : 6

For example, this code:

    mailboxes := make(chan *imap.MailboxInfo, 20)
    go func() {
        imapClient.List("", "*", mailboxes)
    }()
    //列取邮件夹
    for m := range mailboxes {
        mailDirs = append(mailDirs, m.Name)
    }

This is much like the role of PHP in yield, internal and external communication function

 

Guess you like

Origin www.cnblogs.com/taoshihan/p/11913961.html