Go language realizes mutex random number time List
- 2020-06-19 10:30:11
- OfStack
Go language realizes mutex, random number, time, List
import (
"container/list"
"fmt"
"math/rand" // note 2: Random number packages
"sync" // note 1: Packages for asynchronous tasks
"time"
)
type INFO struct {
lock sync.Mutex // note 1 Asynchronous lock:
Name string
Time int64
}
var List *list.List = list.New() // note 3 Initialization: List variable
func main() {
var Info INFO
go func() {
for i := 0; i < 5; i++ {
time.Sleep(time.Duration(1e9 * int64(rand.Intn(5))))// note 2 Random number: rand.Intn(5)<---> 1e9 For scientific counting, 1 * 10 the 9 To the power
Info.lock.Lock()// note 1 Lock:
Info.Name = fmt.Sprint("Name", i) // Remark: Sprint Format its parameters in the default format, concatenate all output generation and return 1 A string. If two adjacent arguments are not strings, a space is added between their output
Info.Time = time.Now().Unix() + 3
Info.lock.Unlock()// note 1 : unlock
List.PushBack(Info)// note 3:List Expression call
}
}()
go Getgoods()
select {}
}
func Getgoods() {
for {
time.Sleep(1e8)
for List.Len() > 0 {// note 3:List Use of objects
N, T := List.Remove(List.Front()).(INFO).name() // note 3 : List Object usage and value.(type) The use of
now := time.Now().Unix() // note 4: Gets the timestamp after the current date conversion
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
}
I'll share an example code of a mutex
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()
}
}