-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpthreadTimersTest.c
92 lines (87 loc) · 2.62 KB
/
pthreadTimersTest.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*****************************************************************************
** Name:pthreadTimerTest.c
** 测试多线程下的sleep/usleep相互干扰效果,验证为线程安全的(10ms级别)
** Author:fivezh
** Date:20130506
** Copyright (c) 2013,All Rights Reserved!
*****************************************************************************/
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
void *thread_child (void *data)
{
int count = 1;
struct timeval tStart, tEnd;
long timeuse;
while(1)
{
count++;
gettimeofday(&tStart,NULL);//取得开始的时间
usleep(4000000); // us=microsecond
//sleep(4); // s=second
gettimeofday(&tEnd,NULL);
//timeuse = 1000000*(tEnd.tv_sec - tStart.tv_sec) + (tEnd.tv_usec - tStart.tv_usec);
//printf("time_us:%d\n",timeuse);
timeuse = 1000*(tEnd.tv_sec - tStart.tv_sec) + (tEnd.tv_usec - tStart.tv_usec)/1000;
printf("i'm %u,time_ms:%ld\n",(unsigned int)pthread_self(),timeuse);
}
}
void *thread_child2 (void *data)
{
int count = 1;
struct timeval tStart, tEnd;
long timeuse;
while(1)
{
count++;
gettimeofday(&tStart,NULL);//取得开始的时间
//usleep(1000);
sleep(3);
gettimeofday(&tEnd,NULL);
//timeuse = 1000000*(tEnd.tv_sec - tStart.tv_sec) + (tEnd.tv_usec - tStart.tv_usec);
//printf("time_us:%d\n",timeuse);
timeuse = 1000*(tEnd.tv_sec - tStart.tv_sec) + (tEnd.tv_usec - tStart.tv_usec)/1000;
printf("i'm %u,time_ms:%ld\n",(unsigned int)pthread_self(),timeuse);
}
}
void *thread_child3 (void *data)
{
int count = 1;
struct timeval tStart, tEnd;
long timeuse;
while(1)
{
count++;
gettimeofday(&tStart,NULL);//取得开始的时间
//usleep(1000);
sleep(5);
gettimeofday(&tEnd,NULL);
//timeuse = 1000000*(tEnd.tv_sec - tStart.tv_sec) + (tEnd.tv_usec - tStart.tv_usec);
//printf("time_us:%d\n",timeuse);
timeuse = 1000*(tEnd.tv_sec - tStart.tv_sec) + (tEnd.tv_usec - tStart.tv_usec)/1000;
printf("i'm %u,time_ms:%ld\n",(unsigned int)pthread_self(),timeuse);
}
}
int main(int argc, char const *argv[])
{
pthread_t ptid, ptid2, ptid3;
int err;
err = pthread_create(&ptid,NULL,thread_child,NULL);
if (err != 0)
{
printf("pthread_create error\n");
}
err = pthread_create(&ptid2,NULL,thread_child2,NULL);
if (err != 0)
{
printf("pthread_create error\n");
}
err = pthread_create(&ptid3,NULL,thread_child3,NULL);
if (err != 0)
{
printf("pthread_create error\n");
}
sleep(21);
return 0;
}