Add a little demo/test code for the `threads' project.
[pintos-anon] / src / threads / test.c
1 #include "threads/test.h"
2 #include <stdio.h>
3 #include "threads/synch.h"
4 #include "threads/thread.h"
5 #include "devices/timer.h"
6
7 static void test_sleep_once (void);
8
9 void
10 test (void) 
11 {
12   test_sleep_once ();
13 //  test_sleep_multiple ();
14 }
15 \f
16 struct sleep_once_data 
17   {
18     int duration;               /* Number of ticks to sleep. */
19     volatile int *counter;      /* Counter to check. */
20     struct semaphore done;      /* Completion semaphore. */
21     struct thread *thread;      /* Thread. */
22   };
23
24 static void sleep_once (void *);
25
26 static void
27 test_sleep_once (void) 
28 {
29   struct sleep_once_data t[5];
30   const int t_cnt = sizeof t / sizeof *t;
31   volatile int counter;
32   int i;
33
34   printf ("\nTesting one sleep per thread...\n");
35
36   /* Start all the threads. */
37   counter = 0;
38   for (i = 0; i < t_cnt; i++)
39     {
40       char name[16];
41       snprintf (name, sizeof name, "once %d", i);
42
43       t[i].duration = i * 10;
44       t[i].counter = &counter;
45       sema_init (&t[i].done, 0, name);
46       t[i].thread = thread_create (name, sleep_once, &t[i]);
47     }
48   
49   /* Wait for all the threads to finish. */
50   for (i = 0; i < t_cnt; i++) 
51     {
52 #ifdef THREAD_JOIN_IMPLEMENTED
53       thread_join (t[i].thread);
54 #else
55       sema_down (&t[i].done);
56 #endif
57     }
58
59   printf ("...done\n");
60 }
61
62 static void
63 sleep_once (void *t_) 
64 {
65   struct sleep_once_data *t = t_;
66
67   /* Sleep. */
68   timer_sleep (t->duration);
69
70   /* Check ordering. */
71   if (*t->counter > t->duration)
72     printf ("%s: Out of order sleep completion (%d > %d)!\n",
73             thread_name (thread_current ()),
74             *t->counter, t->duration);
75   else 
76     {
77       *t->counter = t->duration;
78       printf ("%s: Sleep %d complete\n",
79               thread_name (thread_current ()), t->duration);
80     }
81
82   /* Signal completion. */
83   sema_up (&t->done);
84 }
85