当前位置:网站首页>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
}
}
边栏推荐
- [hard core dry goods] which company is better in data analysis? Choose pandas or SQL
- Debezium series: modify the source code to support drop foreign key if exists FK
- id选择器和类选择器的区别
- 【obs】QString的UTF-8中文转换到blog打印 UTF-8 char*
- Force buckle 1200 Minimum absolute difference
- Android interview classic, 2022 Android interview written examination summary
- Analysis of openh264 decoded data flow
- S7-200SMART利用V90 MODBUS通信控制库控制V90伺服的具体方法和步骤
- C - sequential structure
- 【obs】libobs-winrt :CreateDispatcherQueueController
猜你喜欢
40000 word Wenshuo operator new & operator delete
leetcode刷题:二叉树14(左叶子之和)
[hard core dry goods] which company is better in data analysis? Choose pandas or SQL
Jvmrandom cannot set seeds | problem tracing | source code tracing
redis集群模拟消息队列
图嵌入Graph embedding学习笔记
Bitcoinwin (BCW) was invited to attend Hanoi traders fair 2022
Securerandom things | true and false random numbers
SecureRandom那些事|真伪随机数
Go language | 03 array, pointer, slice usage
随机推荐
Fundamentals of deep learning convolutional neural network (CNN)
okcc呼叫中心有什么作用
期货如何网上开户?安不安全?
The city chain technology Digital Innovation Strategy Summit was successfully held
selenium 元素信息
S7-200SMART利用V90 MODBUS通信控制库控制V90伺服的具体方法和步骤
Bitcoinwin (BCW) was invited to attend Hanoi traders fair 2022
秋招字节面试官问你还有什么问题?其实你已经踩雷了
leetcode刷题:二叉树14(左叶子之和)
Go language | 01 wsl+vscode environment construction pit avoidance Guide
JVMRandom不可设置种子|问题追溯|源码追溯
CADD课程学习(7)-- 模拟靶点和小分子相互作用 (半柔性对接 AutoDock)
Autumn byte interviewer asked you any questions? In fact, you have stepped on thunder
Reinforcement learning - learning notes 4 | actor critical
通配符选择器
third-party dynamic library (libcudnn.so) that Paddle depends on is not configured correctl
C application interface development foundation - form control (5) - grouping control
Wildcard selector
图嵌入Graph embedding学习笔记
What are general items