Go language Learning Notes---concurrency

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Go uses channel and goroutine to develop parallel programs.
GoroutineGoroutine is a normal function, just need to use the reserved word go as the beginning. Ready ("Tea", 2)//normal function call go ready ("Tea", 2)//ready () Run as Goroutine
Example: Package Mainimport ("Time" "FMT") Func-Ready (W string, sec int) {time. Sleep (time. Duration (SEC) * time. Second) fmt. Println (W, "is ready!")} Func main () {Go Ready ("Tea", 2) Go Ready ("Coffee", 1) fmt. Println ("I ' m Waiting") Time . Sleep (5 * time. Second)} output: I ' m waiting//Immediate output coffee is ready!            Output tea is ready! after 1 seconds Output after 2 seconds
Note: The above example if you delete time. Sleep (5 * time. Second) Program output I ' m waiting immediately end running
Example 2:package Main
Import ("FMT" "Runtime")
Func say (s string) {for I: = 0; i < 5; i++ {runtime. () fmt. Println (s)}}
Func main () {Go Say ("world")//Open a new Goroutines execution say ("Hello")//Current Goroutines execution} output: HELLOWORLDHELLOWORLDHELLOWORLDH Elloworldhello

Runtime. Gosched () means that the CPU will give the time slice to others, and the next time it resumes executing the goroutine. By default, the scheduler uses only a single thread, which means that only concurrency is implemented. To play parallel with multi-core processors, call runtime is required to be displayed in our program. Gomaxprocs (N) tells the scheduler to use multiple threads at the same time. Gomaxprocs sets the maximum number of system threads that are running logic code at the same time, and returns the previous settings. If n < 1, the current setting is not changed. After the schedule is improved in the new version of Go, this is removed.

ChannelYou must create a channel using make, such as CI: = make (chan int) cs: = Made (Chan string) CF: = Made (chan interface{}) create channelci for sending and receiving integers, Creates Channelcs for strings, and CHANNELCF uses an empty interface to satisfy various types. Sending or receiving data to the channel is done by a similar operator: <-. The specific action depends on the position of the operator: CI <-1//Send integer 1 to channel CI&LT;-CI//Receive integer from Channel ci i: = &LT;-CI//Receive integer from Channel CI, and save to the I
Example: Package Mainimport (    "Time"     "FMT") var c chan int       //define C as Channelfunc Ready (W string, sec int) of type int {    time. Sleep (time. Duration (SEC) * time. Second)     FMT. Println (W, "is ready!")     C <-1           //Send integer 1 to channel C}func main () {     C = make (chan int)    //Initialize c    go Ready ("Tea", 2)    //Use the reserved word go to start a goroutine&nb Sp   Go Ready ("Coffee", 1)     FMT. Println ("I ' m Waiting")     <-c                    //waits until a value is received from the channel. Note that the received value is discarded if you want to save it with I: = <-c    <-c                    //two goroutines, receive two values} output: I ' m waiting              //Immediate output coffee is reaDy!        &NBSP;//1 seconds output tea is ready!           //2 seconds after output
In the example above, you have to read two times from the channel, and if you don't know how many goroutine are started, you can use the Select keyword. The data entered on the channel can be monitored by select (and other things)
Example 2:package mainimport "FMT"
Func sum (a []int, C Chan int) {sum: = 0 for _, V: = range a {sum + = v} c <-sum//send sum to C }
Func Main () {a: = []int{7, 2, 8,-9, 4, 0}
c: = make (chan int) go sum (A[:len (a)/2], C) Go sum (A[len (a)/2:], c) x, y: = <-c, <-c//Receive from C
Fmt. Println (x, y, x + y)} output result: 17-5 12

Parallel and concurrency: The difference between concurrency and parallelism is that a single processor handles multiple tasks simultaneously and multiple processors or multicore processors simultaneously handle many different tasks. The former is a logical simultaneous occurrence (simultaneous), while the latter is physically occurring simultaneously. concurrency (concurrency), also known as co-occurrence, refers to the ability to handle multiple simultaneous activities, and concurrent events do not necessarily occur at the same time. Parallel (parallelism) refers to the simultaneous occurrence of two concurrent events, with the meaning of concurrency, while concurrency is not necessarily parallel. A metaphor: the difference between concurrency and parallelism is that a person eats three steamed buns and three people at the same time eat three steamed buns
Close Channelx, OK = <-ch When OK is assigned true means that the channel has not been closed and the data can be read. Otherwise OK is assigned to false. In this case, the channel is closed.
Buffered Channels
Go also allows you to specify the buffer size of the channel, which is simply how many elements the channel can store. ch:= make (chan bool, 4) Creates a bool-type channel that can store 4 elements. In this channel, the first 4 elements can be written without blocking. When the 5th element is written, the code blocks until the other goroutine reads some elements from the channel, freeing up space.
Example: Package Main
Import "FMT"
Func Main () {c: = make (chan int, 2)//modify 2 to 1 for error, modify 2 to 3 to operate normally C <-1 C <-2 fmt. Println (<-c) fmt. Println (&LT;-C)} Output results: 12

Range and close

package mainimport "fmt"func fibonacci(n int, c chan int) { x, y := 1, 1 for i := 0; i < n; i++ { c <- x x, y = y, x + y } close(c)}func main() { c := make(chan int, 10) go fibonacci(cap(c), c) for i := range c { fmt.Println(i) }}

Output results: 11235813213455

for i := range cCan continuously read the data inside the channel until the channel is explicitly closed. The above code we see can be explicitly closed channel, producer by keywordclosefunction to close the channel. After the channel is closed, no more data can be sent, and the consumer may pass the syntaxv, ok := <-chTest if the channel is closed. If OK returns false, then the channel has no data and has been closed.

Remember that the channel should be closed at the producer's place, not where it is consumed, so it can easily cause panic

Another thing to remember is that the channel is not like a file, and you don't have to close it often, only if you really don't have any data to send, or you want to explicitly end the range loop.

Select SelectIt is blocked by default and only runs when there is a send or receive in the channel that is listening, and when multiple channel is ready, select randomly chooses one to execute.
Example: Package Main
Import "FMT"
Func Fibonacci (c, quit Chan int) {x, Y: = 1, 1 for {select {case c <-x:x, y = y, X + y case <-quit:fmt. Println ("Quit") Return}}}
Func Main () {c: = make (chan int) Quit: = Do (chan int) go func () {for i: = 0; i <; i++ { Fmt. Println (&LT;-C)} quit <-0} () Fibonacci (C, quit)} output: 11235813213455quit

InselectThere's the default syntax,selectIn fact, a switch-like function, the default is when the channel is not ready to listen to the time of execution (select no longer block waiting for channel).

select {case i := <-c: // use idefault: // 当c阻塞的时候执行这里}
timed outPackage Mainimport "Time" func main () {c: = do (chan int) o: = Make (chan bool) go func () {for { Select {Case V: = <-c:println (v) Case <-time. After (5 * time.        Second): println ("timeout") O <-True Break} }} () <-o} output Result: timeout
Runtime Goroutine
There are several functions in the runtime package that deal with Goroutine: Goexit
Exits the currently executing goroutine, but the defer function also continues to invoke the
Gosched
With the execution permission of the current goroutine, the scheduler schedules other waiting tasks to run and resumes execution from that location at some time
Numcpu
Returns the number of CPU cores
Numgoroutine
Returns the total number of tasks being executed and queued
Gomaxprocs
Used to set the number of CPU cores that can be run








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.