Skip to content

Instantly share code, notes, and snippets.

@pouyatafti
Created October 9, 2016 17:10
Show Gist options
  • Save pouyatafti/9c0a34b3fb15b40a8cbe050e4b3bfa95 to your computer and use it in GitHub Desktop.
Save pouyatafti/9c0a34b3fb15b40a8cbe050e4b3bfa95 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"runtime"
"sync"
// "unsafe"
)
func create(fn string, size int64) error {
f, err := os.OpenFile(fn, os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return err
}
f.Close()
return os.Truncate(fn, size)
}
func maxconc() int {
mp := runtime.GOMAXPROCS(0)
nc := runtime.NumCPU()
if mp < nc {
return mp
}
return nc
}
func main() {
const (
nbytes = byte(10)
nroutns = byte(15)
fn = "./test"
)
var wg sync.WaitGroup
if err := create(fn, int64(nbytes)); err != nil {
panic(err)
}
f, err := os.OpenFile(fn, os.O_RDWR, 0600)
if err != nil {
panic(err)
}
defer f.Close()
defer os.Remove(fn)
fmt.Println("max concurrency:", maxconc())
for i := byte(0); i < nbytes*nroutns; i += nbytes {
wg.Add(1)
go func(i byte) {
defer wg.Done()
fmt.Println(i, "... >")
//b := (*[1]byte)(unsafe.Pointer(&i))[:]
b := make([]byte, nbytes)
for j := byte(0); j < nbytes; j++ {
b[j] = j + i
if _, err := f.WriteAt(b[j:j+1], int64(j)); err != nil {
panic(err)
}
}
fmt.Println("<", b)
}(i)
}
wg.Wait()
bf := make([]byte, nbytes)
if _, err := f.ReadAt(bf, 0); err != nil {
panic(err)
}
ch := make(map[byte]bool)
for j := byte(0); j < nbytes; j++ {
ch[bf[j]/nbytes] = true
}
fmt.Println("read: ", bf, "composed of", len(ch), "routines")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment