Reputation: 5025
I'm trying to implement a communication protocol in C. I need to implement a timer (so that if after some time an ACK has not been received yet, the sender will assume the packet has been lost and will send it again).
In a C-looking-pseudocode I would like to have something like this:
if (!ack_received(seqn) && timer_expired(seqn)) {
send_packet(seqn);
start_timer(seqn);
}
Note: seqn
is the sequence number of the packet being sent. Each packet needs a personal timer.
How to implement timer_expired
and start_timer
? Is there a way to do it without using several threads?
Upvotes: 0
Views: 686
Reputation: 1
Can I implement a single threaded timer in C?
Probably not in pure portable C99 (or single-threaded C11, see n1570).
But in practice, you'll often code for some operating system, and you'll then get some ways to have timers. On Linux, read time(7) first. You'll probably also want to use a multiplexing call such as poll(2) (to which you give a delay). And learn more about other system calls, so read intro(2), syscalls(2) and some good Linux programming book (perhaps the old ALP, freely downloadable).
BTW, it seems that you are coding something network related. You practically need some API for that (e.g. Berkeley sockets), hence you'll probably use something similar to an OS.
Many event loops are single-threaded but are providing some kind of timers.
Or perhaps (if you don't have any OS) you are coding some freestanding C for some small embedded hardware platform (e.g. Arduino-like). Then you have some ways to poll network inputs and setup timers.
Upvotes: 1
Reputation: 67979
depends of the architecture of your system it can be done more or less elegant way.
In the simple program with a single thread just declare the table containing starting timestamps. So the function will just check the difference between the current timestamp, the saved one and the timeout value. You need to implement of course an another function which will initialize the table element for the particular timeout counter.
Upvotes: 0