Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f69a71e

Browse files
20220407
1 parent bd42b47 commit f69a71e

File tree

2 files changed

+83
-2
lines changed

2 files changed

+83
-2
lines changed

‎README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,11 @@ ps:白天上班,晚上更新,尽量日更,比心
5353

5454
[第19章 依赖管理](https://github.com/java-aodeng/golang-examples/blob/master/src/go-19/module_package/get_remote_pack_test.go)
5555

56-
> 并发编程,学go的目的开始了,前面都是基础
56+
> 并发编程
5757
5858
[第20章 协程机制](https://github.com/java-aodeng/golang-examples/blob/master/go-20/groutine_test.go)
5959

60-
第21章 共享内存并发机制
60+
[第21章 共享内存并发机制](https://github.com/java-aodeng/golang-examples/blob/master/go-21/share_mem_test.go)
6161

6262
第22章 CSP并发机制
6363

‎go-21/share_mem_test.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package go_21
2+
3+
import (
4+
"sync"
5+
"testing"
6+
"time"
7+
)
8+
9+
/*
10+
共享内存并发机制 就类似于java里面的锁
11+
12+
都是些很简单的东西,直接看代码
13+
14+
*/
15+
16+
//不加锁的情况
17+
func TestCounter(t *testing.T) {
18+
count := 0
19+
for i := 0; i < 5000; i++ {
20+
go func() {
21+
count++
22+
}()
23+
}
24+
time.Sleep(1 * time.Second)
25+
t.Logf("count=%d", count)
26+
}
27+
28+
//运行结果 结果不是我们预想中的5000,发生了写入的问题,不是线程安全的
29+
//=== RUN TestCounter
30+
//--- PASS: TestCounter (1.02s)
31+
//share_mem_test.go:22: count=4936
32+
//PASS
33+
34+
//加锁的情况
35+
func TestCounterThreadSafe(t *testing.T) {
36+
var mut = sync.Mutex{}
37+
count := 0
38+
for i := 0; i < 5000; i++ {
39+
go func() {
40+
defer func() {
41+
mut.Unlock()
42+
}()
43+
mut.Lock()
44+
count++
45+
}()
46+
}
47+
time.Sleep(1 * time.Second)
48+
t.Logf("count=%d", count)
49+
}
50+
51+
//运行结果 加锁之后结果是预想中的
52+
//=== RUN TestCounterThreadSafe
53+
//--- PASS: TestCounterThreadSafe (1.02s)
54+
//share_mem_test.go:47: count=5000
55+
//PASS
56+
57+
//线程等待
58+
func TestCounterWaitGroup(t *testing.T) {
59+
var mut sync.Mutex
60+
var wg sync.WaitGroup
61+
count := 0
62+
for i := 0; i < 5000; i++ {
63+
wg.Add(1)
64+
go func() {
65+
defer func() {
66+
mut.Unlock()
67+
}()
68+
mut.Lock()
69+
count++
70+
wg.Done()
71+
}()
72+
}
73+
wg.Wait()
74+
t.Logf("count=%d", count)
75+
}
76+
77+
//运行结果
78+
//=== RUN TestCounterWaitGroup
79+
//--- PASS: TestCounterWaitGroup (0.03s)
80+
//share_mem_test.go:73: count=5000
81+
//PASS

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /