Created
May 24, 2014 05:23
-
-
Save joliver/5a433786f6b6ce315924 to your computer and use it in GitHub Desktop.
Simple Disruptor Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"runtime" | |
"time" | |
) | |
// the code below is loosely based upon: https://gist.github.com/tux21b/1218360 | |
// it is only safe on 64-bit CPUs. | |
const BufferSize = 1024 * 16 | |
const BufferMask = BufferSize - 1 | |
const Iterations int64 = 1000000 * 100 | |
var ring [BufferSize]int64 | |
type Cursor struct { | |
value int64 | |
padding [7]int64 | |
} | |
func main() { | |
runtime.GOMAXPROCS(2) | |
var readerBarrier, writerBarrier Cursor | |
started := time.Now() | |
go func() { | |
for sequence, cachedGate := int64(0), int64(0); sequence < Iterations; sequence++ { | |
for sequence >= cachedGate { | |
cachedGate = readerBarrier.value + BufferSize | |
} | |
ring[sequence&BufferMask] = sequence | |
writerBarrier.value = sequence + 1 | |
} | |
}() | |
for sequence, cachedGate := int64(0), int64(0); sequence < Iterations; sequence++ { | |
for sequence >= cachedGate { | |
cachedGate = writerBarrier.value | |
} | |
message := ring[sequence&BufferMask] | |
readerBarrier.value = sequence | |
if message != sequence { | |
panic("Out of sequence") | |
} | |
} | |
finished := time.Now() | |
fmt.Println(Iterations, "send/receive operations in", finished.Sub(started)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment