Skip to content

Commit 83cb015

Browse files
committed
Update
1 parent 933e4d1 commit 83cb015

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

examples/singleapp/count_down_latch/countdownlatch.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77

88
// CountdownLatch は、C#-のCountdownEventやJavaのCountDownLatchと同様の機能を提供する構造体です.
99
type CountdownLatch struct {
10-
count int32
10+
count atomic.Int32
1111
mutex sync.Mutex
1212
cond *sync.Cond
1313
}
@@ -21,7 +21,7 @@ func NewCountdownLatch(initialCount int) *CountdownLatch {
2121
var (
2222
ce CountdownLatch
2323
)
24-
ce.count = int32(initialCount)
24+
ce.count.Store(int32(initialCount))
2525
ce.cond = sync.NewCond(&ce.mutex)
2626

2727
return &ce
@@ -43,7 +43,7 @@ func (me *CountdownLatch) SignalCount(count int) bool {
4343
me.mutex.Lock()
4444
defer me.mutex.Unlock()
4545

46-
newCount := atomic.AddInt32(&me.count, -int32(count))
46+
newCount := me.count.Add(-int32(count))
4747
if newCount <= 0 {
4848
me.cond.Broadcast()
4949
return true
@@ -57,17 +57,21 @@ func (me *CountdownLatch) Wait() {
5757
me.mutex.Lock()
5858
defer me.mutex.Unlock()
5959

60-
for atomic.LoadInt32(&me.count) > 0 {
60+
for me.count.Load() > 0 {
6161
me.cond.Wait()
6262
}
6363
}
6464

6565
// CurrentCount は、現在のカウント値を返します.
6666
func (me *CountdownLatch) CurrentCount() int {
67-
return int(atomic.LoadInt32(&me.count))
67+
me.mutex.Lock()
68+
defer me.mutex.Unlock()
69+
70+
return int(me.count.Load())
6871
}
6972

7073
// Reset は、カウントを指定された値にリセットします.
74+
// リセットすることになるため、強制的にカウント満了したことになり、待機している非同期処理が存在する場合は解除されます.
7175
func (me *CountdownLatch) Reset(count int) {
7276
if count < 0 {
7377
panic("リセットカウントは0以上である必要があります")
@@ -76,5 +80,7 @@ func (me *CountdownLatch) Reset(count int) {
7680
me.mutex.Lock()
7781
defer me.mutex.Unlock()
7882

79-
atomic.StoreInt32(&me.count, int32(count))
83+
me.cond.Broadcast()
84+
85+
me.count.Store(int32(count))
8086
}

examples/singleapp/count_down_latch/main.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,29 +66,29 @@ func proc(_ context.Context) error {
6666
latchCount = 3
6767
)
6868
var (
69-
ce = NewCountdownLatch(latchCount)
70-
wg sync.WaitGroup
69+
latch = NewCountdownLatch(latchCount)
70+
wg sync.WaitGroup
7171
)
7272

7373
for range 2 {
74-
ce.Reset(latchCount)
74+
latch.Reset(latchCount)
7575

7676
for i := range 5 {
7777
wg.Add(1)
7878
go func(i int) {
7979
defer wg.Done()
8080

8181
log.Printf("[%2d] 待機開始", i)
82-
ce.Wait()
82+
latch.Wait()
8383
log.Printf("[%2d] 待機解除", i)
8484
}(i)
8585
}
8686

8787
for range 3 {
8888
<-time.After(time.Second)
8989

90-
log.Printf("現在のカウント: %d\n", ce.CurrentCount())
91-
ce.Signal()
90+
log.Printf("現在のカウント: %d\n", latch.CurrentCount())
91+
latch.Signal()
9292
}
9393

9494
wg.Wait()

0 commit comments

Comments
 (0)