华域联盟 Golang Go语言实现互斥锁、随机数、time、List

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

本文由 华域联盟 原创撰写:华域联盟 » Go语言实现互斥锁、随机数、time、List

转载请保留出处和原文链接:https://www.cnhackhy.com/110441.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

在Go中复制文件最流行的3种方法

Go语言的JSON处理详解

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们