Hi,
I'm trying to develop a program to time limit the execution of a function. In the code below I have a function named Inc
which does a lot of iterations (simulated by the infinite loop). The first part of each iteration is quite long, followed by a second part that should be pretty fast.
I don't mind preempting the execution while in the first part of the code, but I'd like to avoid the alarm going off while doing a write operation on the second part.
My first idea was to turn off the alarm before entering the 'safe region' saving the remaining time. Then after exiting, I would set the alarm up with the saved time. I don't know how to implement this. Could someone help me? Alternative methods are also welcome.
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_t thread;
FILE *fout;
void *Inc(void *param){
int i;
long long int x = 0;
fout = fopen("file.txt", "w");
/* Large number of iterations */
while(1){
int k = 0;
for(i=0; i<5000000; i++)
k += (rand())%3;
x += k;
printf("%lld\n", x);
/* Enter Safe Region */
fprintf(fout, "%lld\n", x);
/* Exit Safe Region */
}
}
void Finish(int param){
pthread_cancel(thread);
fclose(fout);
}
main (){
pthread_attr_t attr;
void *status;
signal(SIGALRM, Finish);
alarm(10);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&thread, &attr, Inc, NULL);
pthread_attr_destroy(&attr);
pthread_join(thread, &status);
printf("Program Finished\n");
}