Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Created March 3, 2017 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbengfort/dcd6a1a36a9670562fe8a04cf836ce49 to your computer and use it in GitHub Desktop.
Save bbengfort/dcd6a1a36a9670562fe8a04cf836ce49 to your computer and use it in GitHub Desktop.
Synchronized, thread safe buffer using mutex embedding
package main
import (
"flag"
"fmt"
"log"
"sync"
"time"
)
var (
safe bool
start time.Time
group *sync.WaitGroup
buffer *Buffer
alphas []string
)
// Buffer is a lockable struct that can concatenate several strings together
// into a single string. Note that string concatenation is associative but is
// not commutative, the order of operations matters.
type Buffer struct {
sync.Mutex // wraps a synchronization flag
buf string // the string being concatenated to
}
// Concat is an unsafe concatenation to the buffer that has to "work" 1 sec.
func (b *Buffer) Concat(s string) {
time.Sleep(1 * time.Second)
b.buf += s
}
// SafeConcat is a thread safe concatenation to the buffer.
func (b *Buffer) SafeConcat(s string) {
b.Lock()
defer b.Unlock()
b.Concat(s)
}
// String prints out the buffer representation
func (b *Buffer) String() string {
return b.buf
}
// A simple routine that writes to a global buffer.
func write(idx int, safe bool) {
// Tell the group you're done at the end of the function.
defer group.Done()
if idx >= len(alphas) {
return
}
if safe {
buffer.SafeConcat(alphas[idx])
} else {
buffer.Concat(alphas[idx])
}
log.Printf("%d ", idx)
}
func main() {
flag.BoolVar(&safe, "safe", false, "use the safe concat method")
flag.Parse()
group = new(sync.WaitGroup)
alphas = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}
buffer = new(Buffer)
start = time.Now()
for i := 0; i < len(alphas); i++ {
group.Add(1)
go write(i, safe)
}
group.Wait()
fmt.Printf("\nresult: %s in %s (safe=%t)\n", buffer, time.Since(start), safe)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment