gpin

package module
v0.0.0-...-b1d26fe Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2021 License: MIT Imports: 3 Imported by: 0

README

gpin

A spinlock implementation for Go.

Requirement

Go 1.17

Installation

go get github.com/hlts2/gpin

Example

package main

import (
	"fmt"
	"time"

	"github.com/hlts2/gpin"
)

type Counter struct {
	l gpin.Spinlock
	v map[string]int
}

func (c *Counter) Increment(key string) {
	c.l.Lock()
	c.v[key]++
	c.l.Unlock()
}

func (c *Counter) Get(key string) int {
	c.l.Lock()
	defer c.l.Unlock()
	return c.v[key]
}

func main() {
	c := Counter{
		v: make(map[string]int),
	}
	for i := 0; i < 100; i++ {
		go c.Increment("example")
	}

	time.Sleep(time.Second)
	fmt.Println(c.Get("example")) // 100
}

Benchmark

goos: linux
goarch: amd64
pkg: github.com/hlts2/gpin
cpu: 11th Gen Intel(R) Core(TM) i9-11900K @ 3.50GHz
BenchmarkMutex
BenchmarkMutex-16       	10193804	       135.3 ns/op	       0 B/op	       0 allocs/op
BenchmarkSpinlock
BenchmarkSpinlock-16    	43065172	        30.98 ns/op	       0 B/op	       0 allocs/op

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSpinlock

func NewSpinlock() sync.Locker

NewSpinlock returns sync.Locker implementation.

Types

type Spinlock

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

Spinlock provides the spinlock.

func (*Spinlock) Lock

func (s *Spinlock) Lock()

Lock locks s. If the lock is already in use, the calling goroutine blocks until unlock.

func (*Spinlock) Unlock

func (s *Spinlock) Unlock()

Unlock unlocks s. It is allowed for one goroutine to lock and then arrange for another goroutine to unlock it.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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