Is there a way to callback a function without creating a new goroutine?

288 Views Asked by At

I am trying to implement Reliable-UDP in golang.

One of the basic features I need to implement is packet-retransmission.

The naive method is as follows:

  1. send a packet;
  2. create a timer (also will create a new goroutine) to check if ACK is received before timer fires.

It is simple, but creation a lot of goroutine is NOT FREE. And I do NOT think implementation of packet-retransmission in TCP uses this method.

So, is there a way to callback a function without creating a new goroutine?

I have checked the post from golang-nuts ( https://groups.google.com/forum/#!topic/golang-nuts/ja8j7wQUB-0), and still can not figure out a solution.

2

There are 2 best solutions below

0
Eden On

You can create one timer object with time.NewTicker this will provide with a channel that sends a message periodically.

0
jch On

You want to create a single priority queue that holds all of the scheduled timeouts. A single goroutine should be checking the head of the priority queue, sleeping until the next timeout, and either execute the associated code or discard it.

Of course, you will need to deal with synchronisation issues. The Java way would be to protect the priority queue by a lock. The more go-ish approach would be to put the timeout-handling goroutine in charge of enqueing timeouts, which it receives over a dedicated channel.

There is a priority queue implementation in package container/heap, but I haven't checked how good it is.