国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Golang > 正文

Go語言實現互斥鎖、隨機數、time、List

2020-04-01 18:52:22
字體:
來源:轉載
供稿:網友

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()  }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 湘潭市| 红安县| 邹城市| 木兰县| 定远县| 许昌市| 东光县| 永州市| 潢川县| 靖安县| 深圳市| 达尔| 三穗县| 左贡县| 隆昌县| 外汇| 泌阳县| 民勤县| 五家渠市| 乌拉特中旗| 石嘴山市| 郁南县| 黑水县| 成都市| 吉木乃县| 河东区| 道孚县| 农安县| 平定县| 万载县| 镇康县| 建阳市| 青川县| 虞城县| 汉寿县| 汨罗市| 逊克县| 四子王旗| 黄陵县| 平乐县| 台中县|