我想使统计例程有条件,以便它只在某些情况下运行,否则它将浪费一半的时间。现在,我有一个去例行公事,作为一个生产者,以满足两个消费者例程通过缓冲渠道。是否有办法使统计例程是有条件的,还是有更好的模式可以遵循?提前感谢您的帮助!
func main() {
options()
go produce(readCSV(loc))
go process()
go statistics() // only on flag
<-done
}
func produce(entries [][]string) {
regex, err := regexp.Compile(reg)
if err != nil {
log.Error(reg + ", is not a valid regular expression")
} else {
for _, each := range entries {
if regex.MatchString(each[col]) {
matches <- each
stats <- each // only on flag
}
}
}
done <- true
}
func process() {
for {
match := <-matches
if len(match) != 0 {
// PROCESS
}
}
}
func statistics() {
for {
stat := <-stats
if len(stat) != 0 {
// STATISTICS
}
}
}发布于 2015-07-08 03:13:35
有条件地这样做是没有错的:
var stats chan []string // Don't initialize stats.
func main() {
options()
go produce(readCSV(loc))
go process()
if flag {
stats = make(chan []string, 1024)
go statistics() // only on flag
}
<-done
}
func produce(entries [][]string) {
regex, err := regexp.Compile(reg)
if err != nil {
log.Error(reg + ", is not a valid regular expression")
} else {
for _, each := range entries {
if regex.MatchString(each[col]) {
matches <- each
if stats != nil {
stats <- each // only on flag
}
}
}
}
close(done)
}
func process() {
for {
select {
case match := <-matches:
if len(match) != 0 {
// PROCESS
}
case <-done:
return
}
}
}
func statistics() {
for {
select {
case stat := <-stats:
if len(stat) != 0 {
// STATISTICS
}
case <-done:
return
}
}
}发布于 2015-07-08 03:14:54
也许你在找旗子包。
import "flag"
var withStats = flag.Boolean("s", false, "Do statistics")
func main() {
flag.Parse()
...
if *withStats == true {
t := statType
size := 100
stats := make(chan, t, size)
go statistics() // only on flag
}
...
}发布于 2015-07-08 03:29:06
如果您更新代码中许多地方的统计信息,您可能需要添加一些助手方法。类似于:
type stats struct {
ch chan []string
}
func (s *stats) update(a []string) {
if s != nil {
s.ch <- a
}
}
func (s *stats) start() {
if s != nil {
s.ch = make(chan []string)
go statistics()
}
}
var s *stats
if enabled {
s = new(stats)
}
s.start()
// later in the code
s.update(each)https://stackoverflow.com/questions/31282829
复制相似问题