-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
hekuangsheng
committed
Apr 19, 2022
1 parent
11d183d
commit 6d2d0da
Showing
2 changed files
with
121 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
} | ||
|
||
} |