多线程环境下定时器存在的问题

时间:2021-08-20 23:32:37

主要注意pause函数、sleep函数及alarm函数。alarm函数不影响工作线程,只影响主线程。sleep函数让主线程休眠。pause挂起工作线程

 

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>
void sig_handler(int signo)
{
        pthread_t pid=pthread_self();
        printf("[%d]get alarm signal\n",pid);
        printf("[%d]set alarm signal\n",pid);
        alarm(2);
}

void *pthread_func()
{
        pthread_t pid=pthread_self();
        printf("[%d]set alarm signal\n",pid);
        alarm(2);
        while(1)
        {
                printf("[%d]pause begin\n",pid);
                pause();
                 printf("[%d]pause end\n",pid);
        }
}

int main(int argc, char **argv)
{
        pthread_t tid;
        pthread_t pid;
        int retval;
        signal(SIGALRM, sig_handler);
        if((retval = pthread_create(&tid, NULL, pthread_func, NULL)) < 0)
        {
                perror("pthread_create");
                _exit(-1);
        }
        while(1)
        {
                printf("[%d]sleep 10 begin\n",pid);
                sleep(10);
                printf("[%d]sleep 10 end\n",pid);
        }
        return 0;
}