Go语言实现互斥锁、随机数、time、List

cmsmdn 2018-10-07

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

相关推荐