Imported Upstream version 3.2.2
[debian/gnuradio] / omnithread / mach.cc
1 //                              Package : omnithread
2 // omnithread/mach.cc           Created : 7/97 lars immisch lars@ibp.de
3 //
4 //    Copyright (C) 1997 Immisch, Becker & Partner
5 //
6 //    This file is part of the omnithread library
7 //
8 //    The omnithread library is free software; you can redistribute it and/or
9 //    modify it under the terms of the GNU Library General Public
10 //    License as published by the Free Software Foundation; either
11 //    version 2 of the License, or (at your option) any later version.
12 //
13 //    This library is distributed in the hope that it will be useful,
14 //    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 //    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 //    Library General Public License for more details.
17 //
18 //    You should have received a copy of the GNU Library General Public
19 //    License along with this library; if not, write to the Free
20 //    Software Foundation, Inc., 51 Franklin Street, Boston, MA  
21 //    02110-1301, USA
22 //
23
24 //
25 // Implementation of OMNI thread abstraction for mach threads
26 //
27 // to the author's pleasure, mach cthreads are very similar to posix threads
28 //
29
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <sys/time.h>
33 #include <mach/cthreads.h>
34 #include "gnuradio/omnithread.h"
35
36 #define DB(x) // x
37 // #include <iostream> or #include <iostream.h> if DB is on.
38
39 #define ERRNO(x) (x)
40
41 //
42 // static variables
43 //
44
45 int omni_thread::init_t::count = 0;
46
47 omni_mutex* omni_thread::next_id_mutex;
48 int omni_thread::next_id = 0;
49
50 static int normal_priority;
51 static int highest_priority;
52
53 static size_t stack_size = 0;
54
55 ///////////////////////////////////////////////////////////////////////////
56 //
57 // Mutex
58 //
59 ///////////////////////////////////////////////////////////////////////////
60
61
62 omni_mutex::omni_mutex(void)
63 {
64   mutex_init(&mach_mutex);      
65 }
66
67
68 omni_mutex::~omni_mutex(void)
69 {
70   mutex_clear(&mach_mutex);     
71 }
72
73
74 void omni_mutex::lock(void)
75 {
76   mutex_lock(&mach_mutex);
77 }
78
79
80 void omni_mutex::unlock(void)
81 {
82   mutex_unlock(&mach_mutex);
83 }
84
85
86
87 ///////////////////////////////////////////////////////////////////////////
88 //
89 // Condition variable
90 //
91 ///////////////////////////////////////////////////////////////////////////
92
93
94 omni_condition::omni_condition(omni_mutex* m) : mutex(m)
95 {
96   condition_init(&mach_cond);
97 }
98
99
100 omni_condition::~omni_condition(void)
101 {
102   condition_clear(&mach_cond);
103 }
104
105 void
106 omni_condition::wait(void)
107 {
108   condition_wait(&mach_cond, &mutex->mach_mutex);
109 }
110
111 typedef struct alarmclock_args {
112   unsigned long secs;
113   unsigned long nsecs;
114   bool wakeup;
115   condition_t condition;
116   mutex_t mutex;
117 };
118
119 any_t alarmclock(any_t arg)
120 {
121   alarmclock_args* alarm = (alarmclock_args*)arg;
122         
123   omni_thread::sleep(alarm->secs, alarm->nsecs);
124
125   mutex_lock(alarm->mutex);
126                         
127   alarm->wakeup = TRUE;
128         
129   condition_signal(alarm->condition);
130                 
131   mutex_unlock(alarm->mutex);
132
133   return (any_t)TRUE;
134 }
135
136 int omni_condition::timedwait(unsigned long abs_secs, unsigned long abs_nsecs)
137 {
138   alarmclock_args alarm;
139
140   omni_thread::get_time(&alarm.secs, &alarm.nsecs, 0, 0);
141         
142   if (abs_secs < alarm.secs || (abs_secs == alarm.secs && abs_nsecs <= alarm.nsecs))
143     return ETIMEDOUT;
144
145   alarm.secs = abs_secs - alarm.secs;
146   if (abs_nsecs <= alarm.nsecs) {
147     alarm.nsecs = 1000000 - alarm.nsecs + abs_nsecs;
148     alarm.secs--;
149   }
150   else {
151     alarm.nsecs = abs_nsecs - alarm.nsecs;
152   }
153
154   alarm.mutex = &mutex->mach_mutex;
155   alarm.condition = &mach_cond;
156   alarm.wakeup = FALSE;
157         
158   cthread_t ct = cthread_fork((cthread_fn_t)alarmclock, (any_t)&alarm);
159   cthread_detach(ct);
160         
161   condition_wait(&mach_cond, &mutex->mach_mutex);
162                 
163   if (alarm.wakeup) {
164     return 0;
165   }
166         
167   // interrupt the alarmclock thread sleep
168   cthread_abort(ct);
169         
170   // wait until it has signalled the condition
171   condition_wait(&mach_cond, &mutex->mach_mutex);
172
173   return 1;
174 }
175
176
177 void omni_condition::signal(void)
178 {
179   condition_signal(&mach_cond);
180 }
181
182
183 void omni_condition::broadcast(void)
184 {
185   condition_signal(&mach_cond);
186 }
187
188
189
190 ///////////////////////////////////////////////////////////////////////////
191 //
192 // Counting semaphore
193 //
194 ///////////////////////////////////////////////////////////////////////////
195
196
197 omni_semaphore::omni_semaphore(unsigned int initial) : c(&m)
198 {
199   value = initial;
200 }
201
202
203 omni_semaphore::~omni_semaphore(void)
204 {
205 }
206
207
208 void 
209 omni_semaphore::wait(void)
210 {
211   omni_mutex_lock l(m);
212
213   while (value == 0)
214     c.wait();
215
216   value--;
217 }
218
219
220 int
221 omni_semaphore::trywait(void)
222 {
223   omni_mutex_lock l(m);
224
225   if (value == 0)
226     return 0;
227
228   value--;
229   return 1;
230 }
231
232
233 void
234 omni_semaphore::post(void)
235 {
236   omni_mutex_lock l(m);
237
238   if (value == 0)
239     c.signal();
240
241   value++;
242 }
243
244
245
246 ///////////////////////////////////////////////////////////////////////////
247 //
248 // Thread
249 //
250 ///////////////////////////////////////////////////////////////////////////
251
252
253
254 //
255 // Initialisation function (gets called before any user code).
256 //
257
258 omni_thread::init_t::init_t(void)
259 {
260   if (count++ != 0)     // only do it once however many objects get created.
261     return;
262
263   //
264   // find base and max priority. 
265   // This is the initial thread, so the max priority of this
266   // thread also applies to any newly created thread.
267   //
268
269   kern_return_t                         error;
270   struct thread_sched_info      info;
271   unsigned int                          info_count = THREAD_SCHED_INFO_COUNT;
272
273   error = thread_info(thread_self(), THREAD_SCHED_INFO, (thread_info_t)&info, &info_count);
274   if (error != KERN_SUCCESS) {
275     DB(cerr << "omni_thread::init: error determining thread_info" << endl);
276     ::exit(1);
277   }
278   else {
279     normal_priority = info.base_priority;
280     highest_priority = info.max_priority;
281   }
282
283   next_id_mutex = new omni_mutex;
284
285   //
286   // Create object for this (i.e. initial) thread.
287   //
288
289   omni_thread* t = new omni_thread;
290
291   if (t->_state != STATE_NEW) {
292     DB(cerr << "omni_thread::init: problem creating initial thread object\n");
293     ::exit(1);
294   }
295
296   t->_state = STATE_RUNNING;
297   
298   t->mach_thread = cthread_self();
299
300   DB(cerr << "initial thread " << t->id() << endl);
301
302   cthread_set_data(t->mach_thread, (any_t)t);
303 }
304
305
306 //
307 // Wrapper for thread creation.
308 //
309
310 extern "C" void*
311 omni_thread_wrapper(void* ptr)
312 {
313   omni_thread* me = (omni_thread*)ptr;
314   
315   DB(cerr << "omni_thread::wrapper: thread " << me->id()
316      << " started\n");
317
318   cthread_set_data(cthread_self(), (any_t)me);
319
320   //
321   // Now invoke the thread function with the given argument.
322   //
323
324   if (me->fn_void != NULL) {
325     (*me->fn_void)(me->thread_arg);
326     omni_thread::exit();
327   }
328   
329   if (me->fn_ret != NULL) {
330     void* return_value = (*me->fn_ret)(me->thread_arg);
331     omni_thread::exit(return_value);
332   }
333   
334   if (me->detached) {
335     me->run(me->thread_arg);
336     omni_thread::exit();
337   } else {
338     void* return_value = me->run_undetached(me->thread_arg);
339     omni_thread::exit(return_value);
340   }
341
342   // should never get here.
343
344   return NULL;
345 }
346
347
348 //
349 // Constructors for omni_thread - set up the thread object but don't
350 // start it running.
351 //
352
353 // construct a detached thread running a given function.
354
355 omni_thread::omni_thread(void (*fn)(void*), void* arg, priority_t pri)
356 {
357   common_constructor(arg, pri, 1);
358   fn_void = fn;
359   fn_ret = NULL;
360 }
361
362 // construct an undetached thread running a given function.
363
364 omni_thread::omni_thread(void* (*fn)(void*), void* arg, priority_t pri)
365 {
366   common_constructor(arg, pri, 0);
367   fn_void = NULL;
368   fn_ret = fn;
369 }
370
371 // construct a thread which will run either run() or run_undetached().
372
373 omni_thread::omni_thread(void* arg, priority_t pri)
374 {
375   common_constructor(arg, pri, 1);
376   fn_void = NULL;
377   fn_ret = NULL;
378 }
379
380 // common part of all constructors.
381
382 void omni_thread::common_constructor(void* arg, priority_t pri, int det)
383 {
384   _state = STATE_NEW;
385   _priority = pri;
386   
387   next_id_mutex->lock();
388   _id = next_id++;
389   next_id_mutex->unlock();
390   
391   thread_arg = arg;
392   detached = det;       // may be altered in start_undetached()
393
394   _dummy       = 0;
395   _values      = 0;
396   _value_alloc = 0;
397   // posix_thread is set up in initialisation routine or start().
398 }
399
400
401 //
402 // Destructor for omni_thread.
403 //
404
405 omni_thread::~omni_thread(void)
406 {
407   DB(cerr << "destructor called for thread " << id() << endl);
408   if (_values) {
409     for (key_t i=0; i < _value_alloc; i++) {
410       if (_values[i]) {
411         delete _values[i];
412       }
413     }
414     delete [] _values;
415   }
416 }
417
418
419 //
420 // Start the thread
421 //
422
423 void 
424 omni_thread::start(void)
425 {
426   omni_mutex_lock l(mutex);
427
428   int rc;
429
430   if (_state != STATE_NEW)
431     throw omni_thread_invalid();
432
433   mach_thread = cthread_fork(omni_thread_wrapper, (any_t)this);
434         
435   _state = STATE_RUNNING;
436
437   if (detached) {
438     cthread_detach(mach_thread);
439   }
440 }
441
442 //
443 // Start a thread which will run the member function run_undetached().
444 //
445
446 void
447 omni_thread::start_undetached(void)
448 {
449   if ((fn_void != NULL) || (fn_ret != NULL))
450     throw omni_thread_invalid();
451
452   detached = 0;
453   start();
454 }
455
456
457 //
458 // join - simply check error conditions & call cthread_join.
459 //
460
461 void 
462 omni_thread::join(void** status)
463 {
464   mutex.lock();
465
466   if ((_state != STATE_RUNNING) && (_state != STATE_TERMINATED)) {
467     mutex.unlock();
468     throw omni_thread_invalid();
469   }
470
471   mutex.unlock();
472
473   if (this == self())   
474     throw omni_thread_invalid();
475
476   if (detached)
477     throw omni_thread_invalid();
478
479   DB(cerr << "omni_thread::join: doing cthread_join\n");
480
481  *status = cthread_join(mach_thread);
482
483   delete this;
484 }
485
486
487 //
488 // Change this thread's priority.
489 //
490
491 void
492 omni_thread::set_priority(priority_t pri)
493 {
494   omni_mutex_lock l(mutex);
495
496   if (_state != STATE_RUNNING)
497     throw omni_thread_invalid();
498
499   _priority = pri;
500
501   kern_return_t rc = cthread_priority(mach_thread, mach_priority(pri), FALSE);
502         
503   if (rc != KERN_SUCCESS)
504     throw omni_thread_fatal(errno);
505 }
506
507 //
508 // create - construct a new thread object and start it running.  Returns thread
509 // object if successful, null pointer if not.
510 //
511
512 // detached version
513
514 omni_thread* 
515 omni_thread::create(void (*fn)(void*), void* arg, priority_t pri)
516 {
517   omni_thread* t = new omni_thread(fn, arg, pri);
518
519   t->start();
520
521   return t;
522 }
523
524 // undetached version
525
526 omni_thread*
527 omni_thread::create(void* (*fn)(void*), void* arg, priority_t pri)
528 {
529   omni_thread* t = new omni_thread(fn, arg, pri);
530
531   t->start();
532
533   return t;
534 }
535
536 //
537 // exit() _must_ lock the mutex even in the case of a detached thread.  This is
538 // because a thread may run to completion before the thread that created it has
539 // had a chance to get out of start().  By locking the mutex we ensure that the
540 // creating thread must have reached the end of start() before we delete the
541 // thread object.  Of course, once the call to start() returns, the user can
542 // still incorrectly refer to the thread object, but that's their problem.
543 //
544
545 void omni_thread::exit(void* return_value)
546 {
547   omni_thread* me = self();
548
549   if (me)
550     {
551       me->mutex.lock();
552
553       if (me->_state != STATE_RUNNING)
554         DB(cerr << "omni_thread::exit: thread not in \"running\" state\n");
555
556       me->_state = STATE_TERMINATED;
557
558       me->mutex.unlock();
559
560       DB(cerr << "omni_thread::exit: thread " << me->id() << " detached "
561          << me->detached << " return value " << return_value << endl);
562
563       if (me->detached)
564         delete me;
565     }
566   else
567     {
568       DB(cerr << "omni_thread::exit: called with a non-omnithread. Exit quietly." << endl);
569     }
570   cthread_exit(return_value);
571 }
572
573 omni_thread* omni_thread::self(void)
574 {
575   omni_thread* me;
576
577   me = (omni_thread*)cthread_data(cthread_self());
578
579   if (!me) {
580     // This thread is not created by omni_thread::start because it
581     // doesn't has a class omni_thread instance attached to its key.
582     DB(cerr << "omni_thread::self: called with a non-ominthread. NULL is returned." << endl);
583   }
584         
585   return me;
586 }
587
588 void omni_thread::yield(void)
589 {
590   cthread_yield();
591 }
592
593 #define MAX_SLEEP_SECONDS (unsigned)4294966     // (2**32-2)/1000
594
595 void
596 omni_thread::sleep(unsigned long secs, unsigned long nanosecs)
597 {
598   if (secs <= MAX_SLEEP_SECONDS) {
599     thread_switch(THREAD_NULL, SWITCH_OPTION_WAIT, secs * 1000 + nanosecs / 1000000);
600     return;
601   }
602
603   unsigned no_of_max_sleeps = secs / MAX_SLEEP_SECONDS;
604
605   for (unsigned i = 0; i < no_of_max_sleeps; i++)
606     thread_switch(THREAD_NULL, SWITCH_OPTION_WAIT, MAX_SLEEP_SECONDS * 1000);
607
608   thread_switch(THREAD_NULL, SWITCH_OPTION_WAIT, 
609                 (secs % MAX_SLEEP_SECONDS) * 1000 + nanosecs / 1000000);
610         
611   return;
612 }
613
614 void
615 omni_thread::get_time(unsigned long* abs_sec, unsigned long* abs_nsec,
616                       unsigned long rel_sec, unsigned long rel_nsec)
617 {
618   int rc;
619   unsigned long tv_sec;
620   unsigned long tv_nsec;
621   struct timeval tv;
622         
623   rc = gettimeofday(&tv, NULL); 
624   if (rc)       throw omni_thread_fatal(rc);
625
626   tv_sec = tv.tv_sec;
627   tv_nsec = tv.tv_usec * 1000;
628
629   tv_nsec += rel_nsec;
630   tv_sec += rel_sec + tv_nsec / 1000000000;
631   tv_nsec = tv_nsec % 1000000000;
632
633   *abs_sec = tv_sec;
634   *abs_nsec = tv_nsec;
635 }
636
637
638 int 
639 omni_thread::mach_priority(priority_t pri)
640 {
641   switch (pri) {
642
643   case PRIORITY_LOW:
644     return 0;
645
646   case PRIORITY_NORMAL:
647     return normal_priority;
648
649   case PRIORITY_HIGH:
650     return highest_priority;
651
652   default:
653     return -1;
654   }
655 }
656
657 void
658 omni_thread::stacksize(unsigned long sz)
659 {
660   stack_size = sz;
661 }
662
663 unsigned long
664 omni_thread::stacksize()
665 {
666   return stack_size;
667 }
668
669
670 //
671 // Dummy thread
672 //
673
674 #error This dummy thread code is not tested. It might work if you're lucky.
675
676 class omni_thread_dummy : public omni_thread {
677 public:
678   inline omni_thread_dummy() : omni_thread()
679   {
680     _dummy = 1;
681     _state = STATE_RUNNING;
682     mach_thread = cthread_self();
683     cthread_set_data(mach_thread, (any_t)this));
684   }
685   inline ~omni_thread_dummy()
686   {
687     cthread_set_data(mach_thread, (any_t)0));
688   }
689 };
690
691 omni_thread*
692 omni_thread::create_dummy()
693 {
694   if (omni_thread::self())
695     throw omni_thread_invalid();
696
697   return new omni_thread_dummy;
698 }
699
700 void
701 omni_thread::release_dummy()
702 {
703   omni_thread* self = omni_thread::self();
704   if (!self || !self->_dummy)
705     throw omni_thread_invalid();
706
707   omni_thread_dummy* dummy = (omni_thread_dummy*)self;
708   delete dummy;
709 }
710
711
712 #define INSIDE_THREAD_IMPL_CC
713 #include "threaddata.cc"
714 #undef INSIDE_THREAD_IMPL_CC