116 }
117 }
118 /*
119 * Yield processor, if needed to be sure locks get
120 * interleaved on a uniprocessor.
121 */
122 if (yield_flag) {
123 if (yield_flag > 0)
124 sched_yield ();
125 else
126 sleep (1);
127 }
128 }
129 /*
130 * Report that we got 'em, and unlock to try again.
131 */
132 printf (
133 "lock backward got all locks, %d backoffs\n", backoffs);
134 pthread_mutex_unlock (&mutex[0]);
135 pthread_mutex_unlock (&mutex[l]);
136 pthread_mutex_unlock (&mutex[2]);
137 sched_yield ();
138 }
139 return NULL;
140 } 141
142 int main (int argc, char *argv[])
143 {
144 pthread_t forward, backward;
145 int status;
146
147 #ifdef sun
148 /*
149 * On Solaris 2.5, threads are not timesliced. To ensure
150 * that our threads can run concurrently, we need to
151 * increase the concurrency level.
152 */
153 DPRINTF (("Setting concurrency level to 2\n"));
154 thr_setconcurrency (2);
155 #endif
156
157 /*
158 * If the first argument is absent, or nonzero, a backoff
159 * algorithm will be used to avoid deadlock. If the first
160 * argument is zero, the program will deadlock on a lock
161 * "collision."
162 */
163 if (argc > 1)
164 backoff = atoi (argv[l]);
165
166 /*
167 * If the second argument is absent, or zero, the two threads
168 * run "at speed." On some systems, especially uniprocessors,
169 * one thread may complete before the other has a chance to run,
170 * and you won't see a deadlock or backoffs. In that case, try
171 * running with the argument set to a positive number to cause
172 * the threads to call sched_yield() at each lock; or, to make
173 * it even more obvious, set to a negative number to cause the
174 * threads to call sleep(l) instead.
175 */
176 if (argc > 2)
177 yield_flag = atoi (argv[2]);
178 status = pthread_create (
179 &forward, NULL, lock_forward, NULL);
180 if (status != 0)
181 err_abort (status, "Create forward");
182 status = pthread_create (
183 &backward, NULL, lock_backward, NULL);
184 if (status != 0)
185 err_abort (status, "Create backward");
186 pthread_exit (NULL);
187 }
Whatever type of hierarchy you choose,
header file. Document it in the project design notes. Write it on your whiteboard. And then tie a string around your finger to be sure that you do not forget.