-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_context_swtich.cc
More file actions
103 lines (93 loc) · 1.84 KB
/
thread_context_swtich.cc
File metadata and controls
103 lines (93 loc) · 1.84 KB
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
93
94
95
96
97
98
99
100
101
102
103
#include<iostream>
#include<vector>
#include<cmath>
#include<cfloat>
#include<map>
#include <iomanip>
#include <limits>
#include <sys/stat.h>
using namespace std;
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include<pthread.h>
// 引用自https://www.jianshu.com/p/0d90b92000c0
int pipes[20][3];
char buffer[10];
int running = 1;
void inti()
{
int i =20;
while(i--)
{
if(pipe(pipes[i])<0)
exit(1);
pipes[i][2] = i;
}
}
void distroy()
{
int i =20;
while(i--)
{
close(pipes[i][0]);
close(pipes[i][1]);
}
}
double self_test()
{
int i =20000;
struct timeval start, end;
gettimeofday(&start, NULL);
while(i--)
{
if(write(pipes[0][1],buffer,10)==-1)
exit(1);
read(pipes[0][0],buffer,10);
}
gettimeofday(&end, NULL);
return (double)(1000000*(end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec)/20000;
}
void *_test(void *arg)
{
int pos = ((int *)arg)[2];
int in = pipes[pos][0];
int to = pipes[(pos + 1)%20][1];
while(running)
{
read(in,buffer,10);
if(write(to,buffer,10)==-1)
exit(1);
}
}
double threading_test()
{
int i = 20;
struct timeval start, end;
pthread_t tid;
while(--i)
{
pthread_create(&tid,NULL,_test,(void *)pipes[i]);
}
i = 10000;
gettimeofday(&start, NULL);
while(i--)
{
if(write(pipes[1][1],buffer,10)==-1)
exit(1);
read(pipes[0][0],buffer,10);
}
gettimeofday(&end, NULL);
running = 0;
if(write(pipes[1][1],buffer,10)==-1)
exit(1);
return (double)(1000000*(end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec)/10000/20;
}
int main()
{
inti();
printf("%6.6f\n",self_test());
printf("%6.6f\n",threading_test());
distroy();
exit(0);
}