Documentation
¶
Overview ¶
Package latch には、ラッチ関連の処理が存在します.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CountDownLatch ¶
type CountDownLatch struct {
// contains filtered or unexported fields
}
CountDownLatch は、指定されたカウント数分の非同期処理が完了するまで 1つ以上のゴルーチンを待機させる非同期イベントです。
Javaの java.util.concurrent.CountDownLatch を参考にしています。
REF: https://docs.oracle.com/javase/jp/8/docs/api/java/util/concurrent/CountDownLatch.html
NewCountDownLatch(int) でラッチを生成し、非同期処理側で CountDown() を呼び出します。 生成時に指定したカウント数分の CountDown() 呼び出しが実施されたタイミングでラッチがオープンとなります。
非同期処理の完了を待機する側は Await() を呼び出し、取得したチャネルを監視します。 ラッチがオープンとなったタイミングで、このチャネルはクローズされます。
Example ¶
package main
import (
"log"
"os"
"sync"
"time"
"github.com/devlights/gomy/latch"
)
func main() {
const (
latchCount = 2
goroutineCount = 4
)
var (
goroutineLog = log.New(os.Stdout, "[goroutine] ", 0)
waiterLog = log.New(os.Stdout, "[waiter ] ", 0)
)
var (
wg sync.WaitGroup
)
// make latch
l := latch.NewCountDownLatch(latchCount)
// start goroutines
wg.Add(goroutineCount)
for i := 0; i < goroutineCount; i++ {
i := i
go func() {
defer func() { wg.Done() }()
time.Sleep(time.Duration(1+i) * 100 * time.Millisecond)
goroutineLog.Printf("done [%d]", i)
l.CountDown()
}()
}
// wait until latch is open
select {
case <-l.Await():
waiterLog.Print("latch opened")
case <-time.After(goroutineCount * time.Second):
waiterLog.Print("time over")
}
// wait until all goroutine is done
wg.Wait()
}
Output: [goroutine] done [0] [goroutine] done [1] [waiter ] latch opened [goroutine] done [2] [goroutine] done [3]
func NewCountDownLatch ¶
func NewCountDownLatch(count int) *CountDownLatch
NewCountDownLatch は、指定したカウント数を使用して *CountDownLatch を生成します。
func (*CountDownLatch) Await ¶
func (c *CountDownLatch) Await() <-chan struct{}
Await は、非同期処理の完了を待機する際に利用できるチャネルを返します。 このチャネルは、ラッチがオープンした際にクローズされます。
func (*CountDownLatch) CountDown ¶
func (c *CountDownLatch) CountDown()
CountDown は、ラッチをオープンするために必要なカウントを1減らします。
Click to show internal directories.
Click to hide internal directories.