您的位置:首页 > 其它

nanosleep()函数使用

2016-07-08 16:24 239 查看
<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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: