A, mutex lock channel
package main 利用mutex: //import ( //"fmt" //"sync" //) //var x = 0 //func increment(wg *sync.WaitGroup, m *sync.Mutex) { // // m.Lock() // x = x + 1 // m.Unlock() // wg.Done() //} //func main() { // var w sync.WaitGroup // var m sync.Mutex // for i := 0; i < 1000; i++ { // w.Add(1) // go increment(&w,&m) // } // w.Wait() // fmt.Println("final value of x", x) //}
利用信道:
import ( "fmt" "sync" ) var x = 0 func increment(wg *sync.WaitGroup, ch chan bool) { ch <- true x = x + 1 <- ch wg.Done() } func main() { var w sync.WaitGroup ch := make(chan bool, 1) for i := 0; i < 1000; i++ { w.Add(1) go increment(&w, ch) } w.Wait() fmt.Println("final value of x", x) }
Second, exception handling
// Exception Handling Package Penalty for main Import " fmt " FUNC main () { // the defer delay the execution, after the implementation of the first registration, even if the function is a serious mistake, it will execute // the defer fmt.Println ( " xxxxxxx " ) // fmt.Println the defer ( " yyyy " ) f1 () F2 () F3 () } FUNC f1 () { fmt.Println ( " f1 " ) } FUNC F2 () { // the defer fmt.Println ( " I need except oh a " ) // the defer FUNC () { // recover () // recovery program //} () The defer FUNC () { IF OK:! = Recover (); OK = nil { // If the abnormality is not showing nil, if the abnormal value is expressed, the value is abnormal signal // exception handling fmt .Println (OK) } } () fmt.Println ( " F2 " ) // the make var A = ([] int, 3,3 ) //fmt.Println(a[4]) // exception handling off, allow the program to continue panic ( "wrong") // initiative thrown //fmt.Println ( " XXXXX " ) } FUNC F3 () { fmt.Println ( " F3 " ) }