我想要添加sync.WaitGroup
Limit(max int)
函数来重新计算WaitGroup
计数器的数量。
所以我在waitgroup.go
打开了go/src/sync
文件并进行了更改,保存了文件并尝试在桌面上的main.go文件中进行测试。当我运行该文件时,它说:
$ go run main.go
wg.Limit undefined (type sync.WaitGroup has no field or method Limit)
要修复此错误消息,我将文件夹从go/src/sync
复制到包含我的main.go
文件的桌面文件夹中,并将导入从sync
更改为./sync
。
这次运行go run main.go
后,我得到了以下输出:
$ go run main.go
sync\mutex.go:14:2: use of internal package not allowed
sync\pool.go:8:2: use of internal package not allowed
sync\rwmutex.go:8:2: use of internal package not allowed
sync\waitgroup.go:8:2: use of internal package not allowed
要修复这些消息,我将go/src/internal
复制到包含我的main.go
文件的桌面上的文件夹中,并修改了./sync
中引用internal/..
的所有文件到{ {1}}
我再次运行它,我得到以下输出:
./internal/..
如何通过修改$ go run main.go
# _/C_/.../sync
sync\mutex.go:20: missing function body for "throw"
sync\pool.go:66: missing function body for "fastrand"
sync\pool.go:249: missing function body for "runtime_registerPoolCleanup"
sync\pool.go:250: missing function body for "runtime_procPin"
sync\pool.go:251: missing function body for "runtime_procUnpin"
sync\runtime.go:14: missing function body for "runtime_Semacquire"
sync\runtime.go:17: missing function body for "runtime_SemacquireMutex"
sync\runtime.go:23: missing function body for "runtime_Semrelease"
sync\runtime.go:36: missing function body for "runtime_notifyListAdd"
sync\runtime.go:39: missing function body for "runtime_notifyListWait"
sync\runtime.go:39: too many errors
的源文件而不接收这些错误来实现我的简单想法?
答案 0 :(得分:0)
我真的不会通过更改标准库来执行此操作,而是将WaitGroup包装起来以跟踪计数器,如下所示:
type wg_limit struct {
wg sync.WaitGroup
current, max int
}
func (wgl *wg_limit) Add(delta int) error {
if wgl.current+delta > wgl.max {
return fmt.Errorf("counter exceeded (current: %d, max: %d)", wgl.current, wgl.max)
}
wgl.current += delta
wgl.wg.Add(delta)
return nil
}
func (wgl *wg_limit) Done() {
wgl.current -= 1
wgl.wg.Done()
}
然后使用max的值初始化wg_limit并使用结果变量,就像WaitGroup一样:
wgl := wg_limit{max: 3}
if err := wgl.Add(1); err != nil {
// go something()
// ...
wgl.Done()
}
如果添加(delta)的增量超过WaitGroup计数器,则返回错误并且WaitGroup不变。
答案 1 :(得分:-1)
在Go的安装中,导航到src
文件夹并运行名为run.bat
的文件,该文件将重新编译所有软件包,删除您描述的第一个错误。