Golang concurrency Goroutine method of Use

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

2013-12-08 WCDJ


In the Go language, you use Goroutine (a lightweight thread managed by the Go Runtime) to implement concurrent programs.

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 of f happens in the New Goroutine.

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


A simple test case:

Package Mainimport ("FMT" "Time") Func main () {//A goroutine are a lightweight thread managed by the Go runtime//Goroutine s run in the same address space, so access to shared memory must is Synchronizedgo say ("World") Say ("Hello") fmt. Println ("---------------1") A: = []int{7, 2, 8,-9, 4, 0}//Channels is a typed conduit through which you can send and rec Eive values with the channel operator, <-//by default, sends and receives blocks until the other side are 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 do to initialize a buffered CHANNELC2: = Make (chan int, 2) C2 <-1 C2 <-2//c2 <-3//error, the send buffer is full that would causes deadlock!fmt. Println (&LT;-C2) fmt. Println (&LT;-C2)//fmt. Println (&LT;-C2)//error, the receive buffer is empty that would causes deadlock too!fmt. Println ("---------------3") C3: = Make (chan int, ten) Go Fibonacci (Cap (C3), C3) for I: = range C3 {Fmt. Println (i)}fmt. Println ("---------------4") C4: = make (chan int) Quit: = Do (chan int) go func () {for i: = 0; i <; i++ {FMT. Println (&LT;-C4)}quit <-0} () fibonacci2 (C4, quit) fmt. Println ("---------------5")//The default case in a select was run if no other case was ready//use a default case to try a Send or receive without blockingtick: = time. Tick (time.millisecond) Boom: = time. After ($ * time.millisecond) for {select {case <-tick:fmt. Println ("tick.") Case <-boom:fmt. Println ("boom!") Returndefault:fmt. Println (".") Time. Sleep (Time.millisecond)}}}func say (s string) {for I: = 0; i < 5; i++ {time. Sleep (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 Fibonac CI (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 would 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 is no more values coming, such as to terminate a range loo Pclose (c)}//The SELECT statement lets a goroutine wait on multiple communication operations//a select blocks until one o F its cases can run and then it executes. It chooses one at random if multiple is 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----- ----------212---------------30112358132134---------------40112358132134quit---------------5   .    . Tick.     .   . Tick.     .   . Tick.     .   . Tick.     .   . boom!*/





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.