Kaynağa Gözat

Fix non-threadsafe gebruik van Random number generator.

Harry de Boer 10 yıl önce
ebeveyn
işleme
377787313d
4 değiştirilmiş dosya ile 15 ekleme ve 18 silme
  1. 5 8
      board/board.go
  2. 4 7
      board/board_test.go
  3. 1 2
      boardserver/main.go
  4. 5 1
      rndtest/main.go

+ 5 - 8
board/board.go

@@ -6,7 +6,6 @@ import (
 	"fmt"
 	"io"
 	"math/rand"
-	"time"
 )
 
 type Board struct {
@@ -15,8 +14,6 @@ type Board struct {
 	Tiles []Tile `json:"tiles"`
 }
 
-var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
-
 const maxIceWidth = 26
 
 // Create a new randomly generated board.
@@ -56,9 +53,9 @@ func (b Board) String() string {
 }
 
 type jsonTile struct {
-	X int `json:"x"`
-	Y int `json:"y"`
-	Type string`json:"type"`
+	X      int    `json:"x"`
+	Y      int    `json:"y"`
+	Type   string `json:"type"`
 	Player string `json:"player,omitempty"`
 }
 
@@ -96,13 +93,13 @@ func (b Board) isIglo(x, y int) bool {
 }
 
 func (b Board) isRock(x, y int) bool {
-	return rnd.Intn(10) > 7
+	return rand.Intn(10) > 7
 }
 
 func (b Board) isIce(x, y int) bool {
 	leftLimit := (b.Cols - maxIceWidth) / 2
 	rightLimit := b.Cols/2 + maxIceWidth/2
-	return x > leftLimit && x < rightLimit && rnd.Intn(maxIceWidth) >= abs((b.Cols/2)-x)
+	return x > leftLimit && x < rightLimit && rand.Intn(maxIceWidth) >= abs((b.Cols/2)-x)
 }
 
 func abs(a int) int {

+ 4 - 7
board/board_test.go

@@ -1,7 +1,6 @@
 package board
 
 import (
-	"fmt"
 	"math/rand"
 	"testing"
 )
@@ -44,10 +43,8 @@ var testBoard = `~~~~~~~~▲▲▲~▲▲~~*~*~~**~*▲****▲▲***▲~▲***~~
 `
 
 func TestNewBoard(t *testing.T) {
-	rnd = rand.New(rand.NewSource(0))
+	rand.Seed(0)
 	b := New(56, 35)
-l
-	fmt.Println(b)
 
 	if testBoard != b.String() {
 		t.Fatalf("Incorrect board:\n %v", b)
@@ -57,7 +54,7 @@ l
 
 func BenchmarkNew(b *testing.B) {
 	for i := 0; i < b.N; i++ {
-		rnd = rand.New(rand.NewSource(0))
+		rand.Seed(0)
 		New(56, 35)
 	}
 }
@@ -65,10 +62,10 @@ func BenchmarkNew(b *testing.B) {
 func BenchmarkRnd(b *testing.B) {
 
 	for i := 0; i < b.N; i++ {
-		rnd = rand.New(rand.NewSource(0))
+		rand.Seed(0)
 
 		for j := 0; j < 56*35; j++ {
-			rnd.Intn(10)
+			rand.Intn(10)
 		}
 	}
 }

+ 1 - 2
boardserver/main.go

@@ -1,14 +1,13 @@
 package main
 
 import (
-	"runtime"
 	"log"
 	"net/http"
 	"pinguin/board"
 )
 
 func main() {
-	runtime.GOMAXPROCS(1)
+	//runtime.GOMAXPROCS(1)
 	http.HandleFunc("/api/board", boardHandler)
 	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
 		w.Write([]byte("Go battlecamp!"))

+ 5 - 1
rndtest/main.go

@@ -1,9 +1,13 @@
 package main
 
+import (
+	"runtime"
+)
+
 var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
 
 func main() {
-	//runtime.GOMAXPROCS(1)
+	runtime.GOMAXPROCS(runtime.NumCPU())
 	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
 		b := board.New(56, 35)
 		w.Header().Set("Content-Type", "text/plain;charset=utf-8")