Go Language Learning Notes (iii)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
  1. Add the keyword go before a function call, this time the call will be executed in a new Goroutine (lightweight thread, coprocessor), and when the called function returns, the Goroutine ends, and if the function has a return value, the return value will be discarded.
  2. Lock mechanism and channel in go language
    Package Mainimport ("FMT" "Sync" "Runtime") var counter int = 0func Count (lock *sync. Mutex) {lock. Lock () counter ++fmt. PRINTLN (counter) lock. Unlock ()}func main () {lock: = &sync. Mutex{}for I: = 0; I < 10; i + + {go Count (lock)}for {lock. Lock () c: = Counterlock. Unlock () runtime. Gosched () if C >= {break}}}

    Package Mainimport ("FMT") func Count (ch Chan int) {FMT. Println ("Counting") Ch <-1}func Main () {CHS: = make ([]chan int, ten) for I: = 0; I < 10;i + + {Chs[i] = make (chan int) g o Count (Chs[i])}for _, ch: = Range (CHS) {<-ch}}
  3. Channel Declaration method
  4. Writing data to the channel
    Ch <-val
  5. Read the data from the channel
    Val: = <-Ch
  6. Select usage
    Select {  case <-chan1:  ///If Chan1 successfully read the data, then make the process of the processing statement case  chan2 <-1:  //If the data is successfully written to Chan2, The case processing statement is  default:  //If none of the above is successful, then the default process is entered}
  7. Close the channel to determine if the channel is closed
    Close the channel, directly using the go built-in close (CH) to determine if the channel is closed, using multiple return value mode x, OK: = <-ch
  8. Runtime. The Gosched () method is used to assign time slices, runtime. NUMCPU () is used to obtain the CPU core number, runtime. Gomaxprocs (16) Set the number of CPU cores that the routine uses
  9. Global uniqueness operation of sync. Once.do (func)

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.