当前位置:网站首页>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
}
}
边栏推荐
- Zhongang Mining: analysis of the current market supply situation of the global fluorite industry in 2022
- Flume series: interceptor filtering data
- Successful entry into Baidu, 35K monthly salary, 2022 Android development interview answer
- DP:树DP
- third-party dynamic library (libcudnn.so) that Paddle depends on is not configured correctl
- 如何安全快速地从 Centos迁移到openEuler
- ICTCLAS用的字Lucene4.9捆绑
- Jvmrandom cannot set seeds | problem tracing | source code tracing
- Base du réseau neuronal de convolution d'apprentissage profond (CNN)
- 大厂面试必备技能,2022Android不死我不倒
猜你喜欢
Do you know several assertion methods commonly used by JMeter?
Worthy of being a boss, byte Daniel spent eight months on another masterpiece
Jvmrandom cannot set seeds | problem tracing | source code tracing
leetcode刷题:二叉树18(最大二叉树)
不愧是大佬,字节大牛耗时八个月又一力作
力扣 729. 我的日程安排表 I
Parler de threadlocal insecurerandom
Inventory of the most complete low code / no code platforms in the whole network: Jiandao cloud, partner cloud, Mingdao cloud, Qingliu, xurong cloud, Jijian cloud, treelab, nailing · Yida, Tencent clo
浅浅的谈一下ThreadLocalInsecureRandom
redis集群模拟消息队列
随机推荐
Base du réseau neuronal de convolution d'apprentissage profond (CNN)
秋招字节面试官问你还有什么问题?其实你已经踩雷了
Thread pool parameters and reasonable settings
Go language | 01 wsl+vscode environment construction pit avoidance Guide
字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
Xaas trap: all things serve (possible) is not what it really needs
Fundamentals of shell programming (Part 8: branch statements -case in)
Gstreamer中的task
Is it safe to open a mobile stock account? Is it reliable?
What is the function of okcc call center
selenium 元素信息
Necessary skills for interview in large factories, 2022android will not die, I will not fall
Jvmrandom cannot set seeds | problem tracing | source code tracing
Fundamentals of shell programming (Chapter 9: loop)
Information / data
Based on vs2017 and cmake GUI configuration, zxing and opencv are used in win10 x64 environment, and simple detection of data matrix code is realized
Four methods of random number generation | random | math | threadlocalrandom | securityrandom
C application interface development foundation - form control (6) - menu bar, toolbar and status bar controls
Securerandom things | true and false random numbers
Bitcoinwin (BCW)受邀参加Hanoi Traders Fair 2022