当前位置:网站首页>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 .
边栏推荐
- Daily question brushing record (XIV)
- QT creator 7-cmake update
- 2022软件测试工程师涨薪攻略,3年如何达到30K
- Character conversion PTA
- opencv 判断点在多边形内外
- Comment développer un plug - in d'applet
- What changes has Web3 brought to the Internet?
- Leetcode simple question: the minimum cost of buying candy at a discount
- Advantages and disadvantages of the "Chris Richardson microservice series" microservice architecture
- thinkphp5.1跨域问题解决
猜你喜欢
A trip to Suzhou during the Dragon Boat Festival holiday
点到直线的距离直线的交点及夹角
Livelocks and deadlocks of concurrency control
A substring with a length of three and different characters in the leetcode simple question
Interprocess communication in the "Chris Richardson microservice series" microservice architecture
Bitbucket installation configuration
Getting started with microservices (resttemplate, Eureka, Nacos, feign, gateway)
Countdown to 92 days, the strategy for the provincial preparation of the Blue Bridge Cup is coming~
[error record] groovy function parameter dynamic type error (guess: groovy.lang.missingmethodexception: no signature of method)
Leetcode simple question check whether all characters appear the same number of times
随机推荐
Depth first DFS and breadth first BFS -- traversing adjacency tables
Concurrency control of performance tuning methodology
2022-07-05: given an array, you want to query the maximum value in any range at any time. If it is only established according to the initial array and has not been modified in the future, the RMQ meth
Leetcode simple question check whether all characters appear the same number of times
Database tuning solution
Oracle views the data size of a table
科技云报道荣膺全球云计算大会“云鼎奖”2013-2022十周年特别贡献奖
Talking about MySQL index
Server optimization of performance tuning methodology
344. Reverse String. Sol
The real situation of programmers
50. Pow(x, n). O(logN) Sol
Countdown to 92 days, the strategy for the provincial preparation of the Blue Bridge Cup is coming~
Common interview questions of redis factory
Assign the output of a command to a variable [repeat] - assigning the output of a command to a variable [duplicate]
The new content of the text component can be added through the tag_ Config set foreground and background colors
Some tutorials install the database on ubantu so as not to occupy computer memory?
database mirroring
Search: Future Vision (moving sword)
数据泄露怎么办?'华生·K'7招消灭安全威胁