nicer formatting
[tridge/junkcode.git] / thread.c
1 #define _REENTRANT 
2 #include <pthread.h>
3 #include <stdio.h>
4 #include <fcntl.h>
5 #include <stdlib.h>
6
7 #define MAX_THREADS 1024
8 #define RSIZE (16*1024)
9 static int num_threads;
10 static size_t read_size;
11 static pthread_t tid[MAX_THREADS]; 
12 static pid_t pid[MAX_THREADS]; 
13
14 static void thread_main(void)
15 {
16         char buf[RSIZE];
17         int fd1, fd2;
18         int i;
19
20         sleep(1);
21
22         fd1 = open("/dev/zero", O_RDONLY);
23         fd2 = open("/dev/null", O_WRONLY);
24         
25         for (i=0;i<read_size;i++) {
26                 if (read(fd1, buf, RSIZE) != RSIZE) {
27                         printf("read failed\n");
28                         exit(1);
29                 }
30                 if (write(fd2, buf, RSIZE) != RSIZE) {
31                         printf("write failed\n");
32                         exit(1);
33                 }
34         }
35         close(fd1);
36         close(fd2);
37 }
38
39
40 static void fork_test(void)
41 {
42         int i;
43         time_t start = time(NULL);
44         
45         for (i=0;i < num_threads; i++) {
46                 if ((pid[i] = fork()) == 0) {
47                         thread_main();
48                         _exit(0);
49                 }
50                 if (pid[i] == (pid_t)-1) {
51                         printf("fork %d failed\n", i);
52                         exit(1);
53                 }
54         }
55         
56         for (i=0;i < num_threads; i++) {
57                 waitpid(pid[i], NULL, 0);
58         }  
59         
60         printf("using fork took %d seconds\n", time(NULL) - start);
61 }
62
63
64 static void pthread_test(void)
65 {
66         int i;
67         time_t start = time(NULL);
68         
69         for (i=0;i < num_threads; i++) {
70                 if (pthread_create(&tid[i], NULL, thread_main, NULL) != 0) {
71                         printf("pthread_create failed\n");
72                         exit(1);
73                 }
74         }
75         
76         for (i=0;i < num_threads; i++) {
77                 pthread_join(tid[i], NULL);
78         }
79         
80         printf("using pthreads took %d seconds\n", time(NULL) - start);
81 }
82
83
84 int main(int argc, char *argv[]) 
85 {
86         if (argc < 2) {
87                 printf("usage: %s <num_threads> <num_loops>\n",argv[0]);
88                 exit(1);
89         }
90         
91         num_threads = atoi(argv[1]);
92         read_size = atoi(argv[2]);
93         
94         if (num_threads > MAX_THREADS) {
95                 printf("max_threads is %d\n", MAX_THREADS);
96                 exit(1);
97         }
98         
99         fork_test();
100         pthread_test();
101         fork_test();
102         pthread_test();
103         
104         printf("all done\n");
105 }  
106