Concurrent programming examples

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

Using the Golang Timer

Scheduled Tasks

func demo(input chan interface{}) {    t1 := time.NewTimer(time.Second * 5)    t2 := time.NewTimer(time.Second * 10)    for {        select {        case msg <- input:            println(msg)        case <-t1.C:            println("5s timer")            t1.Reset(time.Second * 5)        case <-t2.C:            println("10s timer")            t2.Reset(time.Second * 10)        }    }}

Staccato device

func main(){    ticker := time.NewTicker(time.Second)    for t := range ticker.C {        fmt.Println("ticker", t)    }}

Timeout

func main(){    ch1 := make(chan int, 1)    ch2 := make(chan int, 1)    select {        case e1 := <-ch1:        //如果ch1通道成功读取数据,则执行该case处理语句            fmt.Printf("1th case is selected. e1=%v",e1)        case e2 := <-ch2:        //如果ch2通道成功读取数据,则执行该case处理语句            fmt.Printf("2th case is selected. e2=%v",e2)        case <- time.After(2 * time.Second):            fmt.Println("Timed out")    }}

Custom Timers

func main(){    var t *time.Timer    f := func(){        fmt.Printf("Expiration time : %v.\n", time.Now())        fmt.Printf("C`s len: %d\n", len(t.C))    }    t = time.AfterFunc(1*time.Second, f)    //让当前Goroutine 睡眠2s,确保大于内容的完整    //这样做原因是,time.AfterFunc的调用不会被阻塞。它会以一部的方式在到期事件来临执行我们自定义函数f。    time.Sleep(2 * time.Second)}

Personal blog: http://notes.xbug.site

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.