If I am doing something similar to the code below, what happens if in the "doWork" function, the timeout operation fires before the processing goroutine completes - in this case the processing goroutine will be sending data to a remote webservice - does the underlying network socket get closed/cleaned up, or will it start leaking resources? My aim to to give the processing routine a maximum amount of time to complete it's job and timeout the operation if it cannot succeed (in this case, uploading the results in time). Just not sure about the consequences of 'abandoning' the network send and possibly creating a resource leak.
// create a bunch of workers and process some tasksfunc SomeGeneratorFunc(numWorkers int) {// create numWorkers: runtime.NumCPU()workResults := make (chan workItemResult, numWorkers)// have each worker perform the taskfor i := 0; i < numWorkers; i++ {go doWork (getWorkData(), workResults)}// log the work resultsfor i := 0; i < numWorkers; i++ {s := <-workResultslogResult (s)}
}// do the workfunc doWork (wi workItem, result chan workItemResult) {timeout := make(chan workItemResult)ch := make(chan workItemResult)var dummy workItemResult// process the work itemgo func(w workItemResult) {x := processData(w)ch <- sendDataRemote(x) // send the results remotely, return result to channel}(wi)
// Timeout the work operation if it takes 30 seconds or morego func (wi workItemResult) {time.Sleep(time.Duration(30e9))timeout <- wi}(dummy)
Thanks for your comments. I'm not as concerned with the pseudo code specifically, more so with wondering how cleanup happens when you use a timeout in a select - all the examples I've seen don't make it clear the proper way to handle this cleanup.
For instance, what if the "processing" routine is making a database call, or what I was (poorly) trying to represent making a network call in the processing routine - when the timeout in the select "fires" what happens to the processing routine from a resource cleanup standpoint - does the routine continue running to completion, regardless of the fact that it's output will not be used?
If so, then as long as that processing code does cleanup properly (as if it would never be "short-circuited", then I guess it doesn't matter. But if the execution of the timeout, and subsequent return from the containing function doesn't allow the function to complete, then I can see resource leaks occurring.