Golang Small program Test (ii)

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

1. Golang Program Run time display

Package Mainimport ("FMT" "Time" "Math/rand") func main () {rand. Seed (time. Now (). Unix ()) var name stringfor i:=0; i<3; I++{name=fmt. Sprintf ("go_%02d", i) go runroutine (name, time.) Duration (Rand. INTN (5)) *time. Second)}var input string//for waiting goroutine, unless it Exit.fmt.Scanln (&input) fmt. Println ("Done")}func Runroutine (name string, T time. Duration) {T0:=time. Now () Fmt. PRINTLN (Name, "Start at", t0) time. Sleep (t) t1:=time. Now () Fmt. PRINTLN (name, "End at", T1) fmt. PRINTLN (name, "lasted", T1. Sub (t0)) fmt. Println ()}

Operation Result:

go_00 start at 2013-12-05 17:22:34.5337149 +0800 +0800go_01 start at 2013-12-05 17:22:34.5367151 +0800 +0800go_02 STA RT at 2013-12-05 17:22:34.5367151 +0800 +0800go_02 end at 2013-12-05 17:22:36.5548305 +0800 +0800go_02 lasted 2.01811 54sgo_00 end at 2013-12-05 17:22:37.5558878 +0800 +0800go_00 lasted 3.0221729sgo_01 end at 2013-12-05 17:22:38.55494 +0800 +0800go_01 lasted 4.0182298sjDone

2. Using mutexes to control the execution of Goroutine

package mainimport  "FMT" import  "Time" import  "Math/rand" import  "Sync" import  " Runtime "//var total_tickets int32 = 10var mutex = &sync. mutex{} //can be simply written as: Var mutex sync. Mutexfunc sell_tickets (I int, t time. Duration)  {var total_tickets int32 = 10for {mutex. Lock () if total_tickets > 0 {time. Sleep (t) total_tickets--fmt. PRINTLN ("ID:", i,  "  ticket:",  total_tickets)}mutex. Unlock ()}}func main ()  {runtime. Gomaxprocs (4)         //My Computer is a 4-core processor, so I set the 4rand. Seed (time. Now (). Unix ())  //generate random seed for i := 0; i < 5; i++ { // Concurrent 5 Goroutine to sell tickets go sell_tickets (i, time. Duration (Rand. INTN (5)) *time.millisecond)}//wait for the thread to finish executing var input stringfmt. Scanln (&input)//fmt. Println (total_tickets,  "Done")  //how many tickets are printed when exiting?}

3. Use Select to monitor Channel

package main import  "Time"  import  "FMT"  func main ()  {      //creation of two Channel - c1 c2     c1 := make (Chan  string)      c2 := make (chan string)       //Create two goruntine to send data to these two channel      go func ()  {          time. Sleep (time. second * 1)          c1 <-  "Hello"       } ()      go func ()  {          time. Sleep (time. second * 1)          c2 <-  "World"       } ()      //use Select to listen on two channel      For {         select {         case msg1 :=  <-c1:             fmt. Println ("received", &NBSP;MSG1)          case msg2 :=  <-c2:             fmt. Println ("received", &NBSP;MSG2)          case <-time. After (time. SECOND&NBSP;*&NBSP;30):             fmt. Println ("Time out")              break          }     } }

The above code executes time. After is always error: invalid identifier. I don't know why. If you change to default, add sleep and break, because break is written at the end, it causes sleep to continue listening and the break will never be executed.

Package Mainimport "Time" import "FMT" Func Main () {//Create two channel-c1 c2c1: = Make (Chan string) C2: = Make (Chan string)//Create two A goruntine to each of the two channel to send data go func () {time. Sleep (time. Second * 1) C1 <-"Hello"} () go func () {time. Sleep (time. Second * 1) c2 <-"World"}//Use Select to listen for two channelfor {select {case MSG1: = <-c1:fmt. Println ("received", MSG1) case MSG2: = <-c2:fmt. Println ("received", MSG2) Default://default will cause nonblocking FMT. Println ("Nothing received!") Time. Sleep (time. Second)
Break will never execute a break}}}

Close the channel, always close at the sending end:

Package Mainimport "FMT" Import "Time" import "Math/rand" Func Main () {channel: = Make (chan string) rand. Seed (time. Now (). Unix ())//Send a random number of Messagego func () {cnt: = Rand to the channel. INTN (Ten) fmt. PRINTLN ("Message cnt:", CNT) for i:=0; i<cnt; I++{channel <-FMT. Sprintf ("message-%2d", i)}close (channel)//Close Channel} () var + bool = Truevar msg stringfor more {select{// The channel returns two values, one is content, one is Boolcase msg, and more = <-channel:if more {fmt. PRINTLN (msg)}else{fmt. Println ("Channel closed!")}}}

4. Golang Timer

The go language can use Time.newtimer or Time.newticker to set a timer that binds to your current channel and notifies your program via the channel's blocking notification machine.

Package Mainimport "Time" import "FMT" Func Main () {ticker: = time. Newticker (time. Second) go func () {for t: = Range Ticker. C {fmt. Println (t)}} ()//Set a timer,10 to stop tickertimer: = time. Newtimer (Ten * time. Second) <-timer. Cticker.stop () fmt. PRINTLN ("Timer expired!")}

5. Executing commands with CMD in os/exec

Package Mainimport ("bytes" "FMT" "Log" "Os/exec" "strings") func main () {cmd: = Exec.command ("tr", "A-Z", "A-Z") cmd. Stdin = strings. Newreader ("some input") var out bytes. Buffercmd.stdout = &outerr: = cmd. Run () if err! = Nil {log. Fatal (Err)}fmt. Printf ("In all caps:%q\n"), out. String ())}

6. Golang command line parameter parsing

Package Mainimport ("bytes" "FMT" "Log" "Os/exec" "strings") func main () {cmd: = Exec.command ("tr", "A-Z", "A-Z") cmd. Stdin = strings. Newreader ("some input") var out bytes. Buffercmd.stdout = &outerr: = cmd. Run () if err! = Nil {log. Fatal (Err)}fmt. Printf ("In all caps:%q\n"), out. String ())}

This executes:

#如果没有指定参数名, the default value of Go run flagtest.gohost:coolshell.cnport:80debug:false# is specified after the parameter name of the go run flagtest.go-host= localhost-port=22-dhost:localhostport:22debug:true# Usage Error (example: Using unsupported parameter, parameter not =) $ go build flagtest.go$./flagtest- Debug-host Localhost-port=22flag provided but not defined:-debugusage of flagtest:-d=false:enable/disable Debug mode-h Ost= "coolshell.cn": a host name-port=80:a port Numberexit status 2

7. Issues to be aware of when using append

1. Look at the simple code of the paragraph first.
A: = []int{1, 2, 3, 4, 5}
B = Append (A[1:3], 8, 9)
At this time fmt. What is the result of Println (a)?
The answer is: a = [1, 2, 3, 8, 9]

reason: A[1:3] A new slice:b is returned. But this b follows the original space of a.

2. Look at the new one.
A: = []int{1, 2, 3, 4, 5}
B = Append (A[1:3], 8, 9, ten)
At this time fmt. What is the result of Println (a)?
The answer is: a = [1, 2, 3, 4, 5]

reason answer: Because this time the append data exceeds the space size of a. So the system re-opened a space for B. So the data for a will not be changed.

3. In a
A: = Make ([]int, 0, 6)
a = Append (A, 1, 2, 3, 4, 5)
B = Append (A[1:3], 8, 9, ten)
At this time fmt. What is the result of Println (a)?
The answer is: (as you probably guessed) is a = [1, 2, 3, 8, 9]
Why: Take a look at the last answer and you'll see. That is, the slice is based on the cap space and does not exceed the cap space and does not trigger a redistribution of space.

4. Add a
A: = Make ([]int, 0, 6)
B: = A[:3]//Is this statement legal?
The answer is legal, although Len (a) = = 0, but slice is the cap (a). It's just b = [0, 0, 0]


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.