我正在尝试制作一个具有推送和弹出功能的队列结构。
我需要使用10个线程推送和另外10个线程弹出数据,就像我在下面的代码中所做的那样。
问题:
- 我需要打印出我推/弹出了多少,但我不知道该怎么做
- 有没有办法加快我的代码?代码对我来说太慢了
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
}
}
您应该解决一些问题。
-
Queue类型上的方法应该具有指针接收器。否则,每种方法调用将创建当前队列类型的副本,对队列字段的任何更改都将不能持久存在于方法调用本身之外。
-
可以使用
sync.WaitGroup
来等待所有例程完成。这是专门为之设计的。 -
在队列类型中维护线程安全的推送/弹出计数器可以通过使用CCD_ 2封装。
就速度而言,从你的例子来看,我不太确定你想要实现什么。如果您对此进行详细说明,可能会出现任何优化。
下面是我从你的代码中修改的一个例子:
package main
import (
"log"
"runtime"
"sync"
"sync/atomic"
"time"
)
const SizePerThread = 10000000
type Queue struct {
records string
count int64
}
func (q *Queue) push(record chan interface{}) {
record <- time.Now()
newcount := atomic.AddInt64(&q.count, 1)
log.Printf("Push: %d", newcount)
}
func (q *Queue) pop(record chan interface{}) {
<-record
newcount := atomic.AddInt64(&q.count, -1)
log.Printf("Pop: %d", newcount)
}
func main() {
var wg sync.WaitGroup
runtime.GOMAXPROCS(runtime.NumCPU())
record := make(chan interface{}, 1000000)
queue := new(Queue)
// We are launching 20 goroutines.
// Let the waitgroup know it should wait for as many
// of them to finish.
wg.Add(20)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
for j := 0; j < SizePerThread; j++ {
queue.push(record)
}
}()
go func() {
defer wg.Done()
for j := 0; j < SizePerThread; j++ {
queue.pop(record)
}
}()
}
// Wait for all goroutines to finish.
wg.Wait()
}
问题1的答案:正如jimt所建议的,sync/atomic具有原子更新计数器的功能,这可能对您有用。
问题2的答案:降低DATA_SIZE_PER_THREAD的值,或者更好的做法是使用程序
package main
func main() {}
它以更有效的方式产生与您的程序相同的输出。
说真的,我知道你已经写了一个小程序来探索一些概念。但是,您的程序包含许多问题。现在不是担心速度的时候,而是学习一些基本概念的时候。