Go语言实现互斥锁、随机数、time、List
Go语言实现互斥锁、随机数、time、List
import ( "container/list" "fmt" "math/rand" //备注2:随机数的包 "sync" //备注1:异步任务的包 "time" ) type INFO struct { lock sync.Mutex //备注1:异步锁 Name string Time int64 } var List *list.List = list.New() //备注3:初始化List变量 func main() { var Info INFO go func() { for i := 0; i < 5; i++ { time.Sleep(time.Duration(1e9 * int64(rand.Intn(5))))//备注2:随机数rand.Intn(5)<---> 1e9为科学计数法,1 * 10的9次方 Info.lock.Lock()//备注1:上锁 Info.Name = fmt.Sprint("Name", i) //备注: Sprint采用默认格式将其参数格式化,串联所有输出生成并返回一个字符串。如果两个相邻的参数都不是字符串,会在它们的输出之间添加空格 Info.Time = time.Now().Unix() + 3 Info.lock.Unlock()//备注1:解锁 List.PushBack(Info)//备注3:List表达式调用 } }() go Getgoods() select {} } func Getgoods() { for { time.Sleep(1e8) for List.Len() > 0 {//备注3:List对象的使用 N, T := List.Remove(List.Front()).(INFO).name() //备注3:List对象的使用和value.(type)的妙用 now := time.Now().Unix() //备注4:获取当前日期转换后的时间戳 if T-now <= 0 { fmt.Println(N, T, now) continue } time.Sleep(time.Duration((T - now) * 1e9)) fmt.Println(N, T, now) } } } func (i INFO) name() (string, int64) { return i.Name, i.Time }
再给大家分享一个互斥锁的实例代码
package main import ( "fmt" "runtime" "sync" ) var ( counter int wg sync.WaitGroup mutex sync.Mutex ) func main() { wg.Add(2) fmt.Println("Create Goroutines") go incCounter(1) go incCounter(2) fmt.Println("Waiting To Finish") wg.Wait() fmt.Println("Final Counter:", counter) } func incCounter(id int) { defer wg.Done() for count := 0; count < 2; count++ { mutex.Lock() { value := counter runtime.Gosched() value++ counter = value } mutex.Unlock() } }
相关推荐
聪聪李 2020-06-13
jessieHJ 2020-05-31
xinhao 2020-05-28
czsay 2020-05-25
qscool 2020-05-06
xiechao000 2020-04-21
Lexan 2020-04-15
idning 2020-03-08
IBMRational 2020-03-07
zuihaobushi 2020-02-24
Canethui 2020-02-22
蜗牛慢爬的李成广 2020-02-02
明天你好 2020-01-28
yfisaboy 2020-01-19
风吹夏天 2020-01-10
idning 2020-01-06
georgeandgeorge 2019-12-28
oraclemch 2019-12-12
oXiaoChong 2019-12-07