Go語言實現(xiàn)互斥鎖、隨機數(shù)、time、List
更新時間:2018年10月07日 11:03:08 作者:ck_god
這篇文章主要介紹了Go語言實現(xiàn)互斥鎖、隨機數(shù)、time、List的相關(guān)資料,需要的朋友可以參考下
Go語言實現(xiàn)互斥鎖、隨機數(shù)、time、List
import ( "container/list" "fmt" "math/rand" //備注2:隨機數(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:隨機數(shù)rand.Intn(5)<---> 1e9為科學(xué)計數(shù)法,1 * 10的9次方 Info.lock.Lock()//備注1:上鎖 Info.Name = fmt.Sprint("Name", i) //備注: Sprint采用默認(rèn)格式將其參數(shù)格式化,串聯(lián)所有輸出生成并返回一個字符串。如果兩個相鄰的參數(shù)都不是字符串,會在它們的輸出之間添加空格 Info.Time = time.Now().Unix() + 3 Info.lock.Unlock()//備注1:解鎖 List.PushBack(Info)//備注3:List表達式調(diào)用 } }() 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:獲取當(dāng)前日期轉(zhuǎn)換后的時間戳 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() } }
相關(guān)文章
Golang使用lua腳本實現(xiàn)redis原子操作
這篇文章主要介紹了Golang使用lua腳本實現(xiàn)redis原子操作,本文通過實例代碼給大家介紹的非常詳細,對大家的工作或?qū)W習(xí)具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03詳解golang 定時任務(wù)time.Sleep和time.Tick實現(xiàn)結(jié)果比較
本文主要介紹了golang 定時任務(wù)time.Sleep和time.Tick實現(xiàn)結(jié)果比較,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02Golang使用Gin創(chuàng)建Restful API的實現(xiàn)
本文主要介紹了Golang使用Gin創(chuàng)建Restful API的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01go語言調(diào)用c語言的so動態(tài)庫的實現(xiàn)
在Go語言開發(fā)過程中,有時需要調(diào)用C或C++編寫的so動態(tài)庫,本文介紹了如何在Go語言中調(diào)用so庫的步驟和注意事項,包括環(huán)境準(zhǔn)備、編譯生成.so文件、Go文件編寫、以及可能遇到的問題和解決方法,感興趣的可以了解一下2024-10-10