C ++ While loop, usleep () / sleep (), how not to use 90% of the processor? (Ubuntu 12.04)

Suppose I have C ++ code like

#include "myheaderfiles.h"
//..some stuff
//...some more stuff
int main()
{
   double milliseconds;
   int seconds;
   int minutes;
   int timelimit=2;
   ...
   ...
   //...code here that increments 
   //.....milliseconds,seconds, and minutes

   while(minutes <=timelimit)
   {
      //...do stuff
      if(milliseconds>500)
      {
         //...do stuff 
         //...every half second
      } //end if
   } //end while
}//end main

The program will work fine and does what it should do, but it will use 90% + of my processor.

I was asked to use usleep () in my while loop of 100 ms or so, since I really care about doing things every 500 ms anyway. Thus, it starts the processor when it is not needed.

So, I added it to my while loop so

   while(minutes <=timelimit)
   {
      //...do stuff
      if(milliseconds>500)
      {
         //...do stuff 
         //...every half second
      } //end if
      usleep(100000);
   } //end while

It compiles fine, but when I run it, the program will hang right at home and never return. I read somewhere that before calling usleep you need to flush all buffers, so I blushed all file streams and replicas, etc. Etc. Still out of luck.

2 . (), .

, , , , .

while(), , , FPGA, .

- ... , , ? .

+4
3

. 90-100% CPU, - ( , ).
, , ( 100% CPU), , - (, , ).

:

while(blocking_call() != exit_condition)
{
    while(have_work)
        do_work();
}

, , (, setitimer), - . , .

, , , . Ubuntu/Linux , , API, epoll_wait, eventfd, .

+2

, ( OSX, ).

  #include <unistd.h>
  #include <iostream> 

  int main() {
    std::cout << "hello" << std::endl;

    int i = 0;
    while(i < 10) {
      ++i;
      usleep(100000);
      std::cout << "i = " << i << std::endl;                                                                                                                                        
    }
    std::cout << "bye" << std::endl;
    return 0;
  }
0

, , ? , , , ? , , usleep (x), double ? usleep (1) - 1 == 1000 . (x) , .

#include <iostream>
#include <unistd.h>

using namespace std;

#define MILLISECOND 1000
#define SECOND 1000*MILLISECOND

int main(int argc, char *argv[]){
    int time = 20;
    int sec_counter = 0;
    do{     
        cout<<sec_counter<<" second"<<endl;
        usleep(SECOND);
        sec_counter++;
    } while(sec_counter<time+1);
    return 0;
}

500 , usleep (SECOND) usleep (500 * MILLISECOND). , , .

0

Source: https://habr.com/ru/post/1536190/


All Articles