How to implement a counter when using golang's goroutine?
Posted
by
MrROY
on Stack Overflow
See other posts from Stack Overflow
or by MrROY
Published on 2012-09-04T14:37:20Z
Indexed on
2012/09/04
15:38 UTC
Read the original article
Hit count: 473
go
I'm trying to make a queue struct that have push and pop functions.
I need to use 10 threads push and another 10 threads pop data, just like i did in the code below.
Questions : 1. I need to print out how much i have pushed/popped, but i don't know how to do that. 2. Is there anyway to speed up my code ? the code is too slow for me.
package main
import (
"runtime"
"time"
)
const (
DATA_SIZE_PER_THREAD = 10000000
)
type Queue struct {
records string
}
func (self Queue) push(record chan interface{}) {
// need push counter
record <- time.Now()
}
func (self Queue) pop(record chan interface{}) {
// need pop counter
<- record
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
//record chan
record := make(chan interface{},1000000)
//finish flag chan
finish := make(chan bool)
queue := new(Queue)
for i:=0; i<10; i++ {
go func() {
for j:=0; j<DATA_SIZE_PER_THREAD; j++ {
queue.push(record)
}
finish<-true
}()
}
for i:=0; i<10; i++ {
go func() {
for j:=0; j<DATA_SIZE_PER_THREAD; j++ {
queue.pop(record)
}
finish<-true
}()
}
for i:=0; i<20; i++ {
<-finish
}
}
© Stack Overflow or respective owner