Golang:计算工作者自己启动了多少个goroutine?

Here is my problem: a caller will create several goroutines to run my code doWork,

go func() {
    for data := range dataSet {
        doWork(data)
    }
}()

And now, I want to count how many goroutines are started to do this work, though I can not modify or read data from the caller. How can I achieve this?

[update] doWork is passed to caller, for example:

   doWork := func(i int) {
        testArray[i]++
        ...
    }

   Parallelize(workerNumber, doWork)

So I am planning to use a global variable as counter.

runtime.NumGoroutines() should give you a global number, so let's assume you cannot rely on that and you need to count how many goroutines were started by this specific procedure, and not the possibly more complex application.

One solution could be, as you stated, using a global counter. Remember that there are races in this case, therefore you are better using synchronization methods, for example by using atomic operations.

Personally, I do not love globals, therefore a solution that I'd like more could be to use a closure to produce a pair (function, countingvariable) by using a maker function (untested code):

func makeCounted(n int) ([]uint64, func(int)) {
    var counters []uint64 = make([]uint64, n)
    return counters, func(i int) {
        atomic.AddUint64(&counters[i], 1)
        fmt.Println("Doing stuff")
    }
}

howMany, doWork := makeCounted()
Parallelize(workers, doWork)

In the case in which n is unknown (len(dataSet) is unknown), you will have to grow dynamically the size of counters, but you will probably need something like sync.Mutex.