当前位置:网站首页>Go language learning tutorial (XV)
Go language learning tutorial (XV)
2022-07-05 22:19:00 【Game programming】
One 、 Thread to sleep
* Go In language main() Function is the main thread ( coroutines ), The program is executed from top to bottom
* Can pass time Under bag Sleep(n) How many nanoseconds does the program block
// The unit is nanosecond , Indicates how long the jam lasts
//e9 Express 10 Of 9 Power
time.Sleep(1e9)
Two 、 Delay the
* Delay the execution once after the specified time , However, it should be noted that the program does not end when triggered
fmt.Println(" Start ")
//2 Execute the anonymous function in seconds
time.AfterFunc(2e9, func() {
fmt.Println(" Delay delay trigger ")
})
time.Sleep(10e9)// Be sure to sleep , Otherwise the program is over
fmt.Println(" end ")
3、 ... and 、goroutine brief introduction
* Golang One of the most fascinating advantages of is that it supports concurrency at the language level
* stay Golang Medium goroutine( coroutines ) Similar to threads in other languages
* Concurrency and parallelism
* parallel (parallelism) It refers to that different code fragments are supported on different physical processors at the same time
* Concurrent (concurrency) It refers to managing multiple things at the same time , A physical processor may deal with other things halfway after running a certain content
* In general, the performance of concurrency is better than that of parallelism . Because the physical resources of the computer are fixed , Less , And the content that the program needs to execute is a lot . So concurrency is ” Do more with less resources ”
* Several mainstream concurrency models
* Multithreading , Each thread processes only one request , Only after the request ends , The corresponding thread will receive the next request . This mode is in high parallel , Performance overhead is huge .
* Callback based asynchronous IO. A large number of callbacks may occur during the operation of the program, resulting in increased maintenance costs , The process of program execution is not convenient for thinking
* coroutines . There is no need for preemptive calls , It can effectively improve the concurrency of thread tasks , It makes up for the shortcomings of multithreading mode ;Golang Support at the language level , Other languages rarely support
* goroutine The grammar of
* An expression can be a statement
* Expressions can also be functions , Function return value even if there is , It doesn't work , When function execution completes this goroutine Automatic end
go expression
Four 、WaitGroup brief introduction
* Golang in sync Package provides basic synchronization primitives , Such as mutual exclusion lock . except Once and WaitGroup type , Most of them are only applicable to low-level program threads , High level synchronous threads use channel Communication is better
* WaitGroup Waiting group , It's actually a counter , As long as there is something in the counter, it will be blocked
* stay Golang in WaitGroup Exist in sync In bag , stay sync All types in the package should not be copied
* Go In the language standard library WaitGroup There are only three ways
* Add(delta int) Indicates adding an increment to the internal counter (delta), The parameter delta It could be negative
* Done() To reduce WaitGroup The value of the counter , It should be executed at the end of the program . amount to Add(-1)
* Wait() Indicates blocking until WaitGroup The counter for 0
* Use WaitGroup Can be effectively solved goroutine The execution of the main coordination process is not completed , Cause the program to end goroutine Unexecuted problem
var wg sync.WaitGroup
func main() {
for i := 1; i <= 3; i++ {
wg.Add(1)
go demo(i)
}
// Blocking , know WaitGroup All tasks in the queue will be unblocked automatically at the end of execution
fmt.Println(" Start blocking ")
wg.Wait()
fmt.Println(" End of task execution , unblocked ")
}
func demo(index int) {
for i := 1; i <= 5; i++ {
fmt.Printf(" The first %d Execution times ,i The value of is :%d\n", index, i)
}
wg.Done()
}
5、 ... and 、 The mutex
* Go There will be conflicts when multiple coroutines operate on a variable in a language
* go run -race You can view the competition
* have access to sync.Mutex Lock the content
* Usage scenarios of mutex
* Multiple goroutine Access the same function ( Code segment )
* This function operates on a global variable
* To ensure the security of shared variables , Value legitimacy
* Use mutex to simulate ticket window
var (
// Number of votes
num = 100
wg sync.WaitGroup
// The mutex
mu sync.Mutex
)
func sellTicker(i int) {
defer wg.Done()
for {
// Lock , Multiple goroutine Mutually exclusive
mu.Lock()
if num >= 1 {
fmt.Println(" The first ", i, " Windows sold ", num)
num = num - 1
}
// Unlock
mu.Unlock()
if num <= 0 {
break
}
// Add sleep , Prevent the result from appearing in a goroutine in
time.Sleep(time.Duration(rand.Int63n(1000) * 1e6))
}
}
func main() {
// Set random number seed
rand.Seed(time.Now().UnixNano())
// The starting value of the calculator is the same as the number of votes
wg.Add(4)
go sellTicker(1)
go sellTicker(2)
go sellTicker(3)
go sellTicker(4)
wg.Wait()
fmt.Println(" All tickets are sold out ")
}
6、 ... and 、 Read-write lock
* Go In language map Not thread safe , Multiple goroutine At the same time, there will be errors .
* RWMutex You can add multiple read locks or one write lock . Read and write locks cannot exist at the same time .
* map Reading and writing under concurrency needs to be completed in combination with reading and writing locks
* Mutex means that there can only be one lock code at a time goroutine function , The read / write lock indicates the read / write operation of data within the lock range
func main() {
var rwm sync.RWMutex
m := make(map[string]string)
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func(j int) {
// Not locked in map There may be problems when
rwm.Lock()
m["key"+strconv.Itoa(j)] = "value" + strconv.Itoa(j)
fmt.Println(m)
rwm.Unlock()
wg.Done()
}(i)
}
wg.Wait()
fmt.Println(" Program end ")
}
One 、channel
* Every thread is a communication difficulty in every programming language , stay Golang Language level is provided in goroutine Communication between :channel
* channel Different translation materials have different names . Several common names
* The Conduit
* channel
* passageway
* channel It's in-process communication , Every channel Only one type of value can be passed . This type needs to be declared channel When you specify
* channel stay Golang Two main functions in
* Sync
* signal communication
* Go In language channel The key word is chan
* Statement channel The grammar of
var name chan type
var name chan <- type // Just write
var name <- chan type // read-only
name :=make(chan int) // No cache channel
name :=make(chan int,0)// No cache channel
name :=make(chan int,100)// With cache channel
* operation channel The grammar of :( Suppose you define a channel The name is ch)
ch <- value // towards ch Add a value to the
<- ch // from ch A value is taken from
a:=<-ch // from ch Take a value from and assign it to a
a,b:=<-ch// from ch Take out a value and assign it to a, If ch Has been closed or ch No value in ,b by false
* Simple cache free channel code example
* If this code is not from channel The value of c,d=<-ch sentence , At the end of the program go func It's not implemented
* The following code example demonstrates the synchronization operation , Similar to WaitGroup function , At the end of the guarantee procedure goroutine Execution completed
* towards goroutine The content in the code will be blocked goroutine perform , So we need to ch<-1 Put in goroutine The last line of valid code
* Whether to channel Storing data or fetching data will block
* close(channel) close channel, After closing, it is read-only and not writable
func main() {
ch := make(chan int)
go func() {
fmt.Println(" Get into goroutine")
// After adding a content, the console outputs :1 true
//ch<-1
// close ch Console output :0 false
close(ch)
}()
c, d := <-ch
fmt.Println(c, d)
fmt.Println(" End of program execution ")
}
* Use channel Realization goroutine Communication between
* channel In fact, it is the implementation scheme of message communication mechanism , stay Golang Shared memory is not used to complete thread communication in , But use channel Realization goroutine Communication between
func main() {
// be used for goroutine Transfer data between
ch := make(chan string)
// Used to control program execution
ch2 := make(chan string)
go func() {
fmt.Println(" Execute the first goroutine, Wait for the second one goroutine To transfer data ")
content := <-ch
fmt.Println(" The received data is :", content)
ch2 <- " first "
}()
go func() {
fmt.Println(" Go to the second , Start delivering data ")
ch <- " Random content "
close(ch)
fmt.Println(" Send data complete ")
ch2 <- " the second "
}()
result1 := <-ch2
fmt.Println(result1, " Execution completed ")
result2 := <-ch2
fmt.Println(result2, " Execution completed ")
fmt.Println(" End of program execution ")
}
* have access to for range obtain channel Chinese content
* You don't need to be sure channel Number of data in
func main() {
ch:=make(chan string)
ch2:=make(chan int)
go func() {
for i:=97;i<97+26;i++{
ch <- strconv.Itoa(i)
}
ch2<-1
}()
go func() {
for c := range ch{
fmt.Println(" Extracted ",c)
}
}()
<-ch2
fmt.Println(" Program end ")
}
* channel Is safe . Multiple goroutine When operating at the same time , There can only be one at a time goroutine Access data
func main() {
ch := make(chan int)
for i := 1; i < 5; i++ {
go func(j int) {
fmt.Println(j, " Start ")
ch <- j
fmt.Println(j, " end ")
}(i)
}
for j := 1; j < 5; j++ {
time.Sleep(2 * time.Second)
<-ch
}
}
author : Xiao CHENGONG
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
- Analysis of the problem that the cookie value in PHP contains a plus sign (+) and becomes a space
- Wonderful review of the digital Expo | highlight scientific research strength, and Zhongchuang computing power won the digital influence enterprise award
- 航海日答题小程序之航海知识竞赛初赛
- 如何快速体验OneOS
- Installation of VMware Workstation
- Two stage locking protocol for concurrency control
- QT creator 7 beta release
- Pl/sql basic case
- Implementing Lmax disruptor queue from scratch (IV) principle analysis of multithreaded producer multiproducersequencer
- Interview questions for famous enterprises: Coins represent a given value
猜你喜欢
The simple problem of leetcode is to split a string into several groups of length K
Technology cloud report: how many hurdles does the computing power network need to cross?
Database recovery strategy
MySQL actual combat 45 lecture learning (I)
Create a virtual machine on VMware (system not installed)
Pl/sql basic case
MySQL连接断开报错MySQLdb._exceptions.OperationalError 4031, The client was disconnected by the server
Storage optimization of performance tuning methodology
CA certificate trampled pit
Lightweight dynamic monitorable thread pool based on configuration center - dynamictp
随机推荐
A trip to Suzhou during the Dragon Boat Festival holiday
如何快速体验OneOS
Platformio create libopencm3 + FreeRTOS project
Leetcode simple question: the minimum cost of buying candy at a discount
Common interview questions of redis factory
Leetcode simple question check whether all characters appear the same number of times
K210 learning notes (IV) k210 runs multiple models at the same time
Installation of VMware Workstation
Go语言学习教程(十五)
Analyse des risques liés aux liaisons de microservices
如何向mongoDB中添加新的字段附代码(全)
Nacos 的安装与服务的注册
Win11缺少dll文件怎么办?Win11系统找不到dll文件修复方法
Interprocess communication in the "Chris Richardson microservice series" microservice architecture
Blocking of concurrency control
50. Pow(x, n). O(logN) Sol
119. Pascal‘s Triangle II. Sol
Create a virtual machine on VMware (system not installed)
[groovy] groovy dynamic language features (automatic type inference of function arguments in groovy | precautions for function dynamic parameters)
[Yugong series] go teaching course in July 2022 004 go code Notes