Hello everyone,

Recently, I came across this problem where I had to wait on a condition 
variable until either:
1. The condition was met
2. OR a deadline was reached

This is how I implemented a solution:

func DoSomething(ctx context.Context) error {
if _, ok := ctx.Deadline(); ok {
go broadcastOnCon(ctx)
}

cond.L.Lock()
defer cond.L.Unlock()

for <some condition is not met> {
cond.Wait()
if err := ctx.Err(); err != nil {
return err
}
}
}

func broadcastOnCon(ctx context.Context) {
<-ctx.Done()
cond.L.Lock()
defer cond.L.Unlock()
cond.Broadcast()
}

My concern is here is that I am creating way too many go routines.

I looked for help online and stumbled on this 
thread: https://github.com/golang/go/issues/16620

The thread ends with the reference to context.AfterFunc. The documentation 
for this function states:

*AfterFunc arranges to call f in its own goroutine after ctx is canceled. 
If ctx is already canceled, AfterFunc calls f immediately in its own 
goroutine.*

Does this mean that the AfterFunc is pretty much doing what I was doing? Or 
is the internal implementation different? Will my concern of creating too 
many go routines be mitigated if I use AfterFunc?

Thanks in advance. 

Regards,
Ameya

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/21e6b150-9212-4d58-b399-9be9df8af675n%40googlegroups.com.

Reply via email to