package main
import (
"fmt"
"sync"
"time"
)
func main() {
// //defer函数:defer函数会在普通函数返回之后执行。defer函数中可以释放函数内部变量、关闭数据库连接
// defer deferTestPrint()
// num := deferTestPrintData(1)
// //如果是指针接受,会返回内存地址
// fmt.Println("-----", &num, *num)
//go 函数并发执行的,我们无法确定其调用的顺序,因此 每次的调用主函数的返回结果都是不确定的。
// go testGo1()
// go testGo2()
// fmt.Println("-----")
//go >>> sync包提供了2个锁,互斥锁sync.Mutex和读写锁sync.RWMutex
// m := new(sync.Mutex)
// go testSyncMutex1(m)
// go testSyncMutex2(m)
//go >> 信道channel
// var ch1 chan string //普通的channel
// var ch2 chan<- string //只用于写int数据
// var ch3 <-chan string //只用于读int数据
cha := make(chan string)
go testCha1(cha)
go testCha2(cha)
time.Sleep(1 * 1e9)
}
func deferTestPrint() {
fmt.Println("I am is job: deferTestPrint")
}
func deferTestPrintData(num int) *int {
defer func() {
fmt.Println("I am is job: deferTestPrintData")
num++
}()
return &num
}
func testGo1() {
fmt.Println("I am is job: testGo1")
}
func testGo2() {
fmt.Println("I am is job: testGo2")
}
func testSyncMutex1(m *sync.Mutex) {
m.Lock()
//操作
fmt.Println("I am is job: testSyncMutex1")
//需要释放所
defer m.Unlock()
}
func testSyncMutex2(m *sync.Mutex) {
m.Lock()
//操作
fmt.Println("I am is job: testSyncMutex2")
//需要释放所
defer m.Unlock()
}
func testCha1(cs chan string) {
fmt.Println("I am is job: testCha1")
cs <- "testCha1--"
}
func testCha2(cs chan string) {
fmt.Println("I am is job: testCha2")
<-cs
defer close(cs)
}
golang : 简单的协程
stromXu
334
2022-07-22
0