欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-01-29 17:11:36
go语言实现互斥锁、随机数、time、list import ( "container/list" "fmt" "math/rand" //备注...

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