Skip to content

Instantly share code, notes, and snippets.

View deckarep's full-sized avatar
🎯
Focusing

Ralph Caraveo deckarep

🎯
Focusing
View GitHub Profile
@deckarep
deckarep / concurrent_bench.go
Created September 10, 2017 04:10
Concurrent benchmarks of both sync.Map and a regular RWMutex locked map.
func benchmarkRegularStableKeys(b *testing.B, workerCount int) {
runtime.GOMAXPROCS(workerCount)
rm := NewRegularIntMap()
populateMap(b.N, rm)
var wg sync.WaitGroup
wg.Add(workerCount)
// Holds our final results, to prevent compiler optimizations.
@deckarep
deckarep / load_bench.go
Last active September 10, 2017 03:48
Benchmark of sync.Map vs builtin map with Load operations
func BenchmarkLoadRegularFound(b *testing.B) {
nums := nrand(b.N)
rm := NewRegularIntMap()
for _, v := range nums {
rm.Store(v, v)
}
currentResult := 0
b.ResetTimer()
@deckarep
deckarep / delete_bench.go
Last active September 10, 2017 03:47
Benchmark sync.Map vs regular RWMutex map
func BenchmarkDeleteRegular(b *testing.B) {
nums := nrand(b.N)
rm := NewRegularIntMap()
for _, v := range nums {
rm.Store(v, v)
}
b.ResetTimer()
for _, v := range nums {
rm.Delete(v)
@deckarep
deckarep / store_bench.go
Last active September 10, 2017 03:46
Benchmark sync.Map vs regular map for Stores
func nrand(n int) []int {
i := make([]int, n)
for ind := range i {
i[ind] = rand.Int()
}
return i
}
func BenchmarkStoreRegular(b *testing.B) {
nums := nrand(b.N)
@deckarep
deckarep / sync_map_usage.go
Last active September 10, 2017 01:11
Usage of sync.Map
func syncMapUsage() {
fmt.Println("sync.Map test (Go 1.9+ only)")
fmt.Println("----------------------------")
// Create the threadsafe map.
var sm sync.Map
// Fetch an item that doesn't exist yet.
result, ok := sm.Load("hello")
if ok {
@deckarep
deckarep / regular_map.go
Created September 10, 2017 01:04
Regular Thread-Safe Int Map
package RegularIntMap
type RegularIntMap struct {
sync.RWMutex
internal map[int]int
}
func NewRegularIntMap() *RegularIntMap {
return &RegularIntMap{
internal: make(map[int]int),
@deckarep
deckarep / main.go
Created September 6, 2017 04:24
Debouncing Queues in Go
package main
import (
"fmt"
"math/rand"
"os"
"os/signal"
"sync/atomic"
"time"
)
@deckarep
deckarep / unsafe_before_mutex.go
Last active December 22, 2016 20:59
Unsafe without the use of locks
package main
import (
"fmt"
"math/rand"
"time"
)
const totalEnemies = 1
@deckarep
deckarep / safe_after_mutex.go
Last active December 22, 2016 21:23
Demonstrates some safe code with the use of locks.
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
const totalEnemies = 2
@deckarep
deckarep / channels_broken.go
Last active December 21, 2016 04:23
Breaking Go's mantra
func adder(amount int) {
for item := range adderChannel {
item.number += amount
doublerChannel <- item
fmt.Println(item.number) // <-- uh oh!
}
}