xsync

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2023 License: MIT Imports: 3 Imported by: 0

README

About

Go Reference

Some Go concurrency utilities.

Download/Install

go get -u github.com/dushaoshuai/xsync

Usage

Onces

Onces is an object that will try to (if asked) perform a successful action only if a specified interval has elapsed since the last successful action.

Example:

package main

import (
	"fmt"
	"sync"
	"time"

	"github.com/dushaoshuai/xsync"
)

func main() {
	onces := xsync.OnceInterval(time.Second)

	var wg sync.WaitGroup
	for i := 0; i < 10_000_000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			onces.Do(func() error {
				fmt.Println("Only once this second:", time.Now().Second())
				return nil
			})
		}()
	}
	wg.Wait()

	// Sample Output:
	// Only once this second: 30
	// Only once this second: 31
	// Only once this second: 32
	// Only once this second: 33
	// Only once this second: 34
	// Only once this second: 35
	// Only once this second: 36
	// Only once this second: 37
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Onces

type Onces struct {
	// contains filtered or unexported fields
}

Onces is an object that will try to (if asked) perform a successful action only if a specified interval has elapsed since the last successful action. An Onces must not be copied after first use. An Onces may be used by multiple goroutines simultaneously.

Example
package main

import (
	"fmt"
	"sync"
	"time"

	"github.com/dushaoshuai/xsync"
)

func main() {
	onces := xsync.OnceInterval(time.Second)

	var wg sync.WaitGroup
	for i := 0; i < 10_000_000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			onces.Do(func() error {
				fmt.Println("Only once this second:", time.Now().Second())
				return nil
			})
		}()
	}
	wg.Wait()

	// Sample Output:
	// Only once this second: 30
	// Only once this second: 31
	// Only once this second: 32
	// Only once this second: 33
	// Only once this second: 34
	// Only once this second: 35
	// Only once this second: 36
	// Only once this second: 37
}

func OnceInterval

func OnceInterval(interval time.Duration) *Onces

OnceInterval returns a new Onces. It will panic if interval is less than or equal to 0.

func (*Onces) Do

func (o *Onces) Do(f func() error) error

Do calls the function f if and only if the specified interval has elapsed since the last successful call to f. Do considers a call to f succeed if f returns nil. It's ok if f has different values in each invocation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL