nanosleep()函数使用

nanosleep()函数会导致当前的线程将暂停执行,直到rqtp参数所指定的时间间隔。或者在指定时间间隔内有信号传递到当前线程,将引起当前线程调用信号捕获函数或终止该线程。
//线程休眠1500ms
#include 
#include 
#include 
#include 

void* pthread_do(void *arg)
{
    struct timespec ts, ts1;
    int count = 0;

    ts.tv_nsec = 500000000;    // 1500ms
    ts.tv_sec = 1;
    while( 1 )
    {
        printf("sub pthread %d\n", count);
        count++;
        if ( nanosleep(&ts, &ts1) == -1 )
        {
            printf("error!\n");
            exit(1);
        }
    }
    return NULL;
}

int main(void)
{
    pthread_t pthd;
    int count = 0;

    pthd = pthread_create(&pthd, NULL, pthread_do, NULL);

    while ( 1 )
    {
        printf("main pthread %d\n", count);
        count++;
        sleep(1);
    }
    return 0;

}

[gfj@kfjk2 c]$ ./a.out
main pthread 0
sub pthread 0
main pthread 1
sub pthread 1
main pthread 2
sub pthread 2
main pthread 3
main pthread 4
sub pthread 3
main pthread 5
sub pthread 4
main pthread 6
main pthread 7
sub pthread 5
main pthread 8
sub pthread 6
main pthread 9
main pthread 10
sub pthread 7
main pthread 11
sub pthread 8
main pthread 12
main pthread 13
sub pthread 9


你可能感兴趣的:(C++)