我想开发一个程序来限制函数的执行时间。在下面的代码中,我有一个名为Inc
的函数,它执行了很多迭代(由无限循环模拟)。每次迭代的第一部分都很长,然后是第二部分,应该很快。如何设置安全区域的功能的时间限制
我不介意在代码的第一部分抢占执行,但我想避免在第二部分执行写操作时发生报警。
我的第一个想法是在进入“安全区域”之前关闭闹钟,以节省剩余时间。然后在退出后,我会用保存的时间设置闹钟。我不知道如何实现这一点。有人能帮助我吗?替代方法也是受欢迎的。
#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");
}
对不起,我几乎无法理解你说的任何话。我对操作系统知之甚少。使用定时等待似乎是一个好方法,但是你能提供一些参考吗?谢谢! – kunigami 2010-09-02 18:49:08
不容易。如果你不明白什么是锁,信号量和互斥锁,那么首先介绍用pthread和信号量进行编程(例如https://computing.llnl.gov/tutorials/pthreads/,http:// en。 wikipedia.org/wiki/Semaphore_%28programming%29,http://www.opengroup.org/onlinepubs/000095399/basedefs/semaphore.h.html)。一旦你理解了基础知识,我认为我写的应该是合理的。 – 2010-09-02 19:43:16