How to implement a counter when using golang's goroutine?

There are a few things you should fix.

  • The methods on the Queue type should have pointer receivers. Otherwise, every method call will create a copy of the current queue type and any changes to queue fields will not persist beyond the method call itself.

  • Waiting for all routines to finish, can be done using a sync.WaitGroup. This is specifically what it was designed for.

  • Maintaining a thread-safe push/pop counter inside the queue type can be done by using the sync/atomic package.

As far as speed goes, from your example, I am not quite sure what you are trying to achieve. Any optimizations might come up if you elaborate on that a little.

Here is an example I modified from your code:

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()
}

Tags:

Go