Go語言實(shí)現(xiàn)互斥鎖、隨機(jī)數(shù)、time、List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import ( "container/list" "fmt" "math/rand" //備注2:隨機(jī)數(shù)的包 "sync" //備注1:異步任務(wù)的包 "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:隨機(jī)數(shù)rand.Intn(5)<---> 1e9為科學(xué)計(jì)數(shù)法,1 * 10的9次方 Info.lock.Lock()//備注1:上鎖 Info.Name = fmt.Sprint("Name", i) //備注: Sprint采用默認(rèn)格式將其參數(shù)格式化,串聯(lián)所有輸出生成并返回一個(gè)字符串。如果兩個(gè)相鄰的參數(shù)都不是字符串,會(huì)在它們的輸出之間添加空格 Info.Time = time.Now().Unix() + 3 Info.lock.Unlock()//備注1:解鎖 List.PushBack(Info)//備注3:List表達(dá)式調(diào)用 } }() go Getgoods() select {} } func Getgoods() { for { time.Sleep(1e8) for List.Len() > 0 {//備注3:List對(duì)象的使用 N, T := List.Remove(List.Front()).(INFO).name() //備注3:List對(duì)象的使用和value.(type)的妙用 now := time.Now().Unix() //備注4:獲取當(dāng)前日期轉(zhuǎn)換后的時(shí)間戳 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 } |
再給大家分享一個(gè)互斥鎖的實(shí)例代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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() } } |
原文鏈接:http://blog.51cto.com/13914991/2294034