nanosleep()函数使用

<span style="color: rgb(51, 51, 51); font-family: arial, 宋体, sans-serif; font-size: 14px; line-height: 24px; text-indent: 28px;">nanosleep()函数会导致当前的线程将暂停执行,直到rqtp参数所指定的时间间隔。或者在指定时间间隔内有信号传递到当前线程,将引起当前线程调用信号捕获函数或终止该线程。</span>
<span style="color: rgb(51, 51, 51); font-family: arial, 宋体, sans-serif; font-size: 14px; line-height: 24px; text-indent: 28px;">//线程<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">休眠1500ms</span></span>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

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


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值