77
88// CountdownLatch は、C#-のCountdownEventやJavaのCountDownLatchと同様の機能を提供する構造体です.
99type 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 は、現在のカウント値を返します.
6666func (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+ // リセットすることになるため、強制的にカウント満了したことになり、待機している非同期処理が存在する場合は解除されます.
7175func (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}
0 commit comments