HI WELCOME TO KANSIRIS

[go-nuts] Go Routines, Timeouts, and resource cleanup question

Leave a Comment
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 tasks
func SomeGeneratorFunc(numWorkers int) {
// create numWorkers: runtime.NumCPU()
workResults := make (chan workItemResult, numWorkers)

// have each worker perform the task
for i := 0; i < numWorkers; i++ {
go doWork (getWorkData(), workResults)
}

// log the work results
for i := 0; i < numWorkers; i++ {
s := <-workResults
logResult (s)
}
}

// do the work
func doWork (wi workItem, result chan workItemResult) {

timeout := make(chan workItemResult)
ch := make(chan workItemResult)

var dummy workItemResult

// process the work item
go 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 more
go func (wi workItemResult) {
time.Sleep(time.Duration(30e9))
timeout <- wi
}(dummy)

select {
case result = <- ch:
log.Println ("Processing finished")
case result = <- timeout:
log.Println("Processing took too long")
}

return
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.