Text written to stdout is not displayed until program termination

In this example, I just print numbers from 0 to 9, with a delay after each. However, instead of leaking numbers into the exit window, there is a long pause (with the spinner’s icons turned around), and then all numbers are displayed immediately (tested both in Chromium 44.0 and Firefox 40.0.3).

Can I immediately record to stdout?

#include <stdio.h>

void time_waster( int reps=100 ) {
   static volatile unsigned counter=0;
   for ( int a=0; a<reps; a++ ) {
      for ( int b=0; b<1000*1000; b++ ) counter++;
   }
}

int main() {
  for ( int i=0; i<10; i++ ) {
     fprintf(stdout,"%d\n",i);
     fflush(stdout);
     time_waster();
  }
}

JavaScript and HTML are built using

emcc -Wall -Werror -o temp.html count.c

By the way, the combined size of the generated HTML + JavaScript for this small example is approximately 600 KB (14619 lines), so debugging in the browser would be a non-trivial task.

Note. I had the same problem with std::coutin C ++ (also with an explicit reset), but decided to write the question in C as a simplification of the problem.


, , node.js:

node temp.js

, HTML, Emscripten.

+4
2

, , emscripten_set_main_loop Emterpreter-Async.

https://github.com/kripken/emscripten/wiki/Emterpreter

#include <stdio.h>
#include <emscripten/emscripten.h>

void time_waster( int reps=100 ) {
   static volatile unsigned counter=0;
   for ( int a=0; a<reps; a++ ) {
      for ( int b=0; b<1000*1000; b++ ) counter++;
   }
}

int main() {
  for ( int i=0; i<10; i++ ) {
     fprintf(stdout,"%d\n",i);
     fflush(stdout);
     emscripten_sleep(0);
     time_waster();
  }
}

em++ -Wall -Werror -o temp.html count.cpp -s EMTERPRETIFY=1 -s EMTERPRETIFY_ASYNC=1 -s EMTERPRETIFY_WHITELIST="['_main']" -Oz

+2
+3

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


All Articles