当前位置:网站首页>Go language learning tutorial (XV)
Go language learning tutorial (XV)
2022-07-05 19:53:00 【Little Chen Gong】
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
}
}
边栏推荐
- 软件测试是干什么的?学习有啥要求?
- 司空见惯 - 英雄扫雷鼠
- What are general items
- Common - Hero Minesweeper
- Do you know several assertion methods commonly used by JMeter?
- Reinforcement learning - learning notes 4 | actor critical
- Is it safe to open a mobile stock account? Is it reliable?
- JVMRandom不可设置种子|问题追溯|源码追溯
- C application interface development foundation - form control (5) - grouping control
- Debezium series: record the messages parsed by debezium and the solutions after the MariaDB database deletes multiple temporary tables
猜你喜欢
CADD课程学习(7)-- 模拟靶点和小分子相互作用 (半柔性对接 AutoDock)
Force buckle 1200 Minimum absolute difference
leetcode刷题:二叉树12(二叉树的所有路径)
【合集- 行业解决方案】如何搭建高性能的数据加速与数据编排平台
leetcode刷题:二叉树10(完全二叉树的节点个数)
Zhongang Mining: analysis of the current market supply situation of the global fluorite industry in 2022
redis集群模拟消息队列
Securerandom things | true and false random numbers
Complete interview questions for interviewers and senior Android engineers in front-line Internet enterprises
Force buckle 729 My schedule I
随机推荐
14. Users, groups, and permissions (14)
Webuploader file upload drag upload progress monitoring type control upload result monitoring control
leetcode刷题:二叉树14(左叶子之和)
软件测试是干什么的?学习有啥要求?
-v parameter of GST launch
[Collection - industry solutions] how to build a high-performance data acceleration and data editing platform
Debezium series: modify the source code to support UNIX_ timestamp() as DEFAULT value
[C language] string function and Simulation Implementation strlen & strcpy & strcat & StrCmp
城链科技数字化创新战略峰会圆满召开
字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
安卓面试宝典,2022Android面试笔试总结
再忙不能忘安全
That's awesome. It's enough to read this article
Android interview classic, 2022 Android interview written examination summary
The difference between ID selector and class selector
Where is the operation of new bonds? Is it safer and more reliable to open an account
Wildcard selector
Is it safe for Guohai Securities to open an account online?
司空见惯 - 英雄扫雷鼠
Is it safe to open a mobile stock account? Is it reliable?