计算模逆

您所在的位置:网站首页 矩阵的模怎么计算 计算模逆

计算模逆

#计算模逆| 来源: 网络整理| 查看: 265

Is this a bad style, should I have something like a WaitGroup?

A wait group solves a different problem.

In general, to be a responsible go citizen here and ensure your code runs and tidies up behind itself, you may need to do a combination of:

Signal to the spawned goroutines to stop their calculations when the result of the computation has been found elsewhere. Ensure a synchronous process waits for the goroutines to stop before returning. This is not mandatory if they properly respond to the signal in #1, but if you don't wait, there will be no guarantee they have terminated before the parent goroutine continues.

In your example program, which performs this task and then quits, there is strictly no need to do either. As this comment indicates, your program's main method terminates upon a satisfactory answer being found, at which point the program will end, any goroutines will be summarily terminated, and the operating system will tidy up any consumed resources. Waiting for goroutines to stop is unnecessary.

However, if you wrapped this code up into a library or it became part of a long running "inverse prime calculation" service, it would be desirable to tidy up the goroutines you spawned to avoid wasting cycles unnecessarily. Additionally, in general, you may have other scenarios in which goroutines store state, hold handles to external resources, or hold handles to internal objects which you risk leaking if not properly tidied away – it is desirable to properly close these.

Communicating the requirement to stop working

There are several approaches to communicate this. I don't claim this is an exhaustive list! (Please do suggest other general-purpose methods in the comments or by proposing edits to the post.)

Using a special channel

Signal the child goroutines by closing a special "shutdown" channel reserved for the purpose. This exploits the channel axiom:

A receive from a closed channel returns the zero value immediately

On receiving from the shutdown channel, the goroutine should immediately arrange to tidy any local state and return from the function. Your earlier question had example code which implemented this; a version of the pattern is:

func myGoRoutine(shutdownChan


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3