Skip to content

Commit

Permalink
并发
Browse files Browse the repository at this point in the history
  • Loading branch information
hekuangsheng committed Apr 19, 2022
1 parent 11d183d commit 6d2d0da
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 0 deletions.
63 changes: 63 additions & 0 deletions sync_mutex/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* @Author: your name
* @Date: 2022-04-19 18:28:21
* @LastEditTime: 2022-04-19 18:30:00
* @LastEditors: Please set LastEditors
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
* @FilePath: /golang-base/sync_mutex/main.go
*/
package main

import (
"fmt"
"sync"
"time"
)

var (
sum int

mutex sync.Mutex
)

func main() {

for i := 0; i < 100; i++ {

go add(10)

}

for i := 0; i < 10; i++ {

go fmt.Println("和为:", readSum())

}

time.Sleep(2 * time.Second)

}

//增加了一个读取sum的函数,便于演示并发

func readSum() int {

mutex.Lock()

defer mutex.Unlock()

b:=sum

return b

}

func add(i int) {

mutex.Lock()

defer mutex.Unlock()

sum += i

}
58 changes: 58 additions & 0 deletions sync_once/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* @Author: your name
* @Date: 2022-04-19 18:28:07
* @LastEditTime: 2022-04-19 18:31:49
* @LastEditors: your name
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
* @FilePath: /golang-base/sync_once/main.go
*/
package main

import (
"fmt"
"sync"
)

func main() {

doOnce()

}

func doOnce() {

var once sync.Once

onceBody := func() {

fmt.Println("Only once")

}

//用于等待协程执行完毕

done := make(chan bool)

//启动10个协程执行once.Do(onceBody)

for i := 0; i < 10; i++ {

go func() {

//把要执行的函数(方法)作为参数传给once.Do方法即可

once.Do(onceBody)

done <- true

}()

}

for i := 0; i < 10; i++ {

<-done

}

}

0 comments on commit 6d2d0da

Please sign in to comment.