Created
December 6, 2016 00:45
-
-
Save Arxcis/9812abd9c60311cfe2617c039a8d12bd to your computer and use it in GitHub Desktop.
Testing out 10 concurrent threads that each count at a random pace
This file contains 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" | |
"math/rand" | |
"time" | |
) | |
func main () { | |
goRoutineTest() | |
} | |
func goRoutineTest() { | |
workers := []Worker {{},{},{},{},{},{},{},{},{},{}} | |
for i := 0; i < 10; i ++ { | |
go count(i, &workers[i]) // fires off 10 go-routines - count(i int, outside *Worker) | |
} | |
time.Sleep(time.Millisecond * 100000) // wait 100 seconds | |
fmt.Println("\n\n") // Print final result | |
i := 0 | |
for i < 10 { | |
fmt.Println(" Worker ", i, " : ", workers[i].counter, " counts -", | |
" Time spent: ", workers[i].timeSpent, "\n") | |
i++ | |
} | |
} | |
type Worker struct { // Struct declaration | |
counter int | |
timeSpent time.Duration | |
} | |
func NewWorker() Worker { // constructor function | |
worker := Worker{} | |
worker.counter = 0 | |
worker.timeSpent = 0 | |
return worker | |
} | |
func count ( id int, outsider *Worker) { | |
var tempTime time.Duration | |
for outsider.counter < 1000 { | |
fmt.Println("worker ", id, " : ", outsider.counter) | |
tempTime = time.Millisecond * time.Duration(rand.Intn(10000)) // Random wait for each thread | |
time.Sleep(tempTime) | |
outsider.timeSpent += tempTime // Sum total time spent | |
outsider.counter ++ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment