我们在下面有一个代码,它每秒都在滴答作响,它工作得很好。当我们有 //select 和 insert 查询需要处理每一秒时,问题就开始了,我们注意到时间间隔在 1 到 10 秒之间。因此,我们实际上错过了一些要完成的处理。知道如何克服这个问题吗?是不是我们需要每秒创建一个单独的线程?谢谢。
void * reader_thread (void * arg) {
while (1) {
if (flag) {
struct timeval tv;
char timeBuf[10],secondBuf1[100],queryBuf1[500],queryBuf2[500];
char buff[20] = {0};
gettimeofday (&tv, NULL);
//fprintf (stderr, "[%d.%06d] Flag set to 1 on ", tv.tv_sec, tv.tv_usec);
tv.tv_sec -= 5;
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(&tv.tv_sec));
printf("\nTime is %s", buff);
//select and insert queries
fprintf (stderr, " %s\n", buff);
flag = 0;
}
usleep (100); // will skew the processing but not signal delivery
}
return NULL;
}
void callback (int sig) {
flag = 1; // this is the only thing the callback does
}
int main () {
timer_t tid = 0;
pthread_t thread;
struct itimerspec it;
char *localServer = "localhost", *remoteServer = "localhost";
char *localUser = "user1", *remoteUser = "user2";
char *localPassword = "****", *remotePassword = "*****";
char *localDatabase = "db1", *remoteDatabase = "db1";
localConn = mysql_init(NULL), remoteConn = mysql_init(NULL);
if (!mysql_real_connect(localConn, localServer,
localUser, localPassword, localDatabase, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(localConn));
exit(1);
}
pthread_create (&thread, NULL, reader_thread, NULL);
signal (SIGALRM, callback);
it.it_value.tv_sec = 1;
it.it_value.tv_nsec = 0;
it.it_interval.tv_sec = 1;
it.it_interval.tv_nsec = 0;
timer_create (CLOCK_REALTIME, NULL, &tid);
timer_settime (tid, 0, &it, NULL);
while (1) sleep (100);
return 0;
}
编辑代码。
sigset_t sigset;
sigfillset(&sigset);
if (pthread_sigmask(
SIG_BLOCK,
&sigset,
NULL))
{
perror("pthread_sigmask");
}
pthread_create (&thread, NULL, reader_thread, NULL);
//sigset_t sigset;
//sigemptyset(&sigset);
sigaddset(&sigset, SIGALRM);
if (pthread_sigmask(
SIG_UNBLOCK,
&sigset,
NULL))
{
perror("pthread_sigmask");
}