Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Factory ¶
type Factory struct {
// contains filtered or unexported fields
}
Factory offers OnceWaiter which is identified according to key string.
Example ¶
package main
import (
"fmt"
"sync"
"time"
"github.com/daichitakahashi/oncewait"
)
func main() {
var factory oncewait.Factory
const key = "example"
processFunc := func() {
defer factory.Refresh(key)
fmt.Println("start heavy process.")
time.Sleep(time.Second) // do something
fmt.Println("process finished.")
}
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
factory.Get(key).Do(processFunc)
fmt.Println("done.")
wg.Done()
}()
wg.Add(1)
go func() {
factory.Get(key).Do(processFunc)
fmt.Println("done.")
wg.Done()
}()
wg.Wait()
}
}
Output: start heavy process. process finished. done. done. start heavy process. process finished. done. done.
func (*Factory) Get ¶
func (f *Factory) Get(key string) *OnceWaiter
Get returns instance of OnceWaiter associated with the key. In the first Get call, new instance is set.
type OnceWaiter ¶
type OnceWaiter struct {
// contains filtered or unexported fields
}
OnceWaiter is an object that will perform exactly one action. But wait for finish of first Do.
Example ¶
package main
import (
"fmt"
"sync"
"time"
"github.com/daichitakahashi/oncewait"
)
func main() {
once := oncewait.New()
processFunc := func() {
fmt.Println("start heavy process.")
time.Sleep(time.Second) // do something
fmt.Println("process finished.")
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
once.Do(processFunc)
fmt.Println("done.")
wg.Done()
}()
wg.Add(1)
go func() {
once.Do(processFunc)
fmt.Println("done.")
wg.Done()
}()
wg.Wait()
}
Output: start heavy process. process finished. done. done.
func (*OnceWaiter) Do ¶
func (o *OnceWaiter) Do(f func())
Do calls the function f and only if Do is being called for the first time for this instance of OnceWaiter, same as standard package's sync.Once. While function f is executing, second call waits for finish.