-1

I have problem with running function every x second. My application:

  1. create, bind socket,

  2. listen on that socket,

  3. accept all incoming connection and creates a new thread for each of them,

  4. send and receive some data,

  5. and now in loop should send data every 1.5 sec, 5 sec and 10 sec.

I try do this like that(where "time" should be time in milliseconds/nanoseconds):

while(true)
{
    if(fmod(time, 1.5)==0)
    {
        /*sending data*/
    }
    if(fmod(time, 5)==0)
    {
        /*sending data*/
    }
    if(fmod(time, 10)==0)
    {
        /*sending data*/
    }
}

When I use time() data are sent multiple times per second, because time() has precision to one second. Could you give me advice what function I need to use to get the time in high precision?

I use Linux

Question 2: How I can end program (perhaps by using any key) when threads running?

dragosht
  • 3,177
  • 2
  • 20
  • 30
DarthBoa
  • 113
  • 1
  • 6
  • Is the time you are talking about equal to `std::time(NULL)` at initialization? Could you edit your question to show us the declaration of this variable please ? – axelduch Sep 10 '14 at 10:01

2 Answers2

2

1) Well, to have a higher resolution timer you can use clock_gettime, an example to get the realtime clock can be found here.

2) I'd say this is not a very good design, why not use a timer with a constant interval that would be rescheduled with the 1.5s, 5s and 10s intervals and would perform the sending? That way you do not have to block the main thread and can either wait for keyboard input in it or do whatever you need to wait for termination.

Community
  • 1
  • 1
Rudolfs Bundulis
  • 11,058
  • 2
  • 27
  • 56
1
  1. Your method is not a good one. First of all - you can't simply compare to zero using floating point arithmetics. You may get 0.0000000000001 in operations that should return zero. Second - if one of your send freezes for some time, another send will be late. And at last but not the least - looping in a while is a waste of CPU. Instead you can use Linux timer functions, and asynchronous IO.

  2. The best way to end a multithreaded program is to catch a signal (SIGINT or SIGTERM or whatever you use) and stop all of your threads, free resources and then quit.