This is a follow-up question to Using a thread in C++ to report progress of computations.
Suppose that I have a for
loop which executes run_difficult_task()
many times, and I would like to infer how far the loop has advanced. I used to write:
int i;
for (i=0; i < 10000; ++i) {
run_difficult_task(i);
if (i % 100 == 0) {
printf("i = %d\n", i);
}
}
but the main problem with such approach is that executing run_difficult_task()
might literally take forever (by being stuck in an infinite loop, etc.), so I would like to get a progress report in every k
seconds by means of printing out the value of the loop variable i
.
I found quite a rich literature on this site regarding object-oriented multithreading (of which I am not really familiar with) in various programming languages, but the questions I found doing this in C-style seem quite outdated. Is there a platform-independent, C11 way to do what I want? If there is not any, then I would be interested in methods working in unix and with gcc.
Note: I do not wish to run various instances of run_difficult_task
in parallel (with, for example, OpenMP), but I want to run the for
loop and the reporting mechanism in parallel.
Related: How to "multithread" C code and How do I start threads in plain C?