1 #include "threads/test.h"
3 #include "threads/synch.h"
4 #include "threads/thread.h"
5 #include "devices/timer.h"
7 static void test_sleep (int iterations);
16 /* Based on a test originally submitted for Stanford's CS 140 in
17 winter 1998 by Rob Baesman <rbaesman@cs.stanford.edu>, Ben
18 Taskar <btaskar@cs.stanford.edu>, and Toli Kuznets
19 <tolik@cs.stanford.edu>. */
20 struct sleep_thread_data
22 int64_t start; /* Start time. */
23 int duration; /* Number of ticks to sleep. */
24 int iterations; /* Number of iterations to run. */
25 int *product; /* Largest product so far. */
26 struct lock *lock; /* Lock on access to `product'. */
27 struct semaphore done; /* Completion semaphore. */
28 tid_t tid; /* Thread ID. */
31 static void sleeper (void *);
34 test_sleep (int iterations)
36 struct sleep_thread_data threads[5];
37 const int thread_cnt = sizeof threads / sizeof *threads;
44 "Testing %d sleeps per thread.\n"
45 "If successful, product of iteration count and\n"
46 "sleep duration will appear in nondescending order.\n",
49 /* Start all the threads. */
51 lock_init (&lock, "product");
52 start = timer_ticks ();
53 for (i = 0; i < thread_cnt; i++)
55 struct sleep_thread_data *t;
58 snprintf (name, sizeof name, "thread %d", i);
61 t->duration = (i + 1) * 10;
62 t->iterations = iterations;
63 t->product = &product;
65 sema_init (&t->done, 0, name);
66 t->tid = thread_create (name, PRI_DEFAULT, sleeper, t);
69 /* Wait for all the threads to finish. */
70 for (i = 0; i < thread_cnt; i++)
72 #ifdef THREAD_JOIN_IMPLEMENTED
73 thread_join (threads[i].tid);
75 sema_down (&threads[i].done);
85 struct sleep_thread_data *t = t_;
88 for (i = 1; i <= t->iterations; i++)
91 int new_product = i * t->duration;
93 timer_sleep ((t->start + new_product) - timer_ticks ());
95 lock_acquire (t->lock);
96 old_product = *t->product;
97 *t->product = new_product;
98 lock_release (t->lock);
100 printf ("%s: duration=%d, iteration=%d, product=%d\n",
101 thread_name (), t->duration, i, new_product);
103 if (old_product > new_product)
104 printf ("%s: Out of order sleep completion (%d > %d)!\n",
105 thread_name (), old_product, new_product);
108 /* Signal completion. */