GoLang之Concurrency協程goroutine使用方法

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

2013-12-08 wcdj


在go語言中,使用goroutine(a lightweight thread managed by the Go runtime)來實現並發程式。

go f(x, y, z)

starts a new goroutine running

f(x, y, z)

The evaluation of f, x, y, and z happens in the current goroutine and the execution off happens in the new goroutine.

Goroutines run in the same address space, so access to shared memory must be synchronized. Thesync package provides useful primitives, although you won't need them much in Go as there are other primitives. (See the next slide, Channels.http://tour.golang.org/#64)


簡單的測試案例:

package mainimport ("fmt""time")func main() {// A goroutine is a lightweight thread managed by the Go runtime//  Goroutines run in the same address space, so access to shared memory must be synchronizedgo say("world")say("hello")fmt.Println("---------------1")a := []int{7, 2, 8, -9, 4, 0}// Channels are a typed conduit through which you can send and receive values with the channel operator, <-// By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variablesc := make(chan int)go sum(a[:len(a)/2], c)go sum(a[len(a)/2:], c)x, y := <-c, <-c // receive from cfmt.Println(x, y, x+y)fmt.Println("---------------2")// Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channelc2 := make(chan int, 2)c2 <- 1c2 <- 2//c2 <- 3// error, the send buffer is full that will causes deadlock!fmt.Println(<-c2)fmt.Println(<-c2)//fmt.Println(<-c2)// error, the receive buffer is empty that will causes deadlock too!fmt.Println("---------------3")c3 := make(chan int, 10)go fibonacci(cap(c3), c3)for i := range c3 {fmt.Println(i)}fmt.Println("---------------4")c4 := make(chan int)quit := make(chan int)go func() {for i := 0; i < 10; i++ {fmt.Println(<-c4)}quit <- 0}()fibonacci2(c4, quit)fmt.Println("---------------5")// The default case in a select is run if no other case is ready// Use a default case to try a send or receive without blockingtick := time.Tick(100 * time.Millisecond)boom := time.After(500 * time.Millisecond)for {select {case <-tick:fmt.Println("tick. ")case <-boom:fmt.Println("BOOM!")returndefault:fmt.Println("    .")time.Sleep(50 * time.Millisecond)}}}func say(s string) {for i := 0; i < 5; i++ {time.Sleep(100 * time.Millisecond)fmt.Println(s)}}func sum(a []int, c chan int) {sum := 0for _, v := range a {sum += v}c <- sum // send sum to c}func fibonacci(n int, c chan int) {x, y := 0, 1for i := 0; i < n; i++ {c <- xx, y = y, x+y}// Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic// Another note: Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loopclose(c)}// The select statement lets a goroutine wait on multiple communication operations// A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are readyfunc fibonacci2(c, quit chan int) {x, y := 0, 1for {select {case c <- x:x, y = y, x+ycase <-quit:fmt.Println("quit")return}}}/*output:helloworldhelloworldhelloworldhelloworldhello---------------1world17 -5 12---------------212---------------30112358132134---------------40112358132134quit---------------5    .    .tick.     .    .tick.     .    .tick.     .    .tick.     .    .BOOM!*/





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.