File: thread-h.html

package info (click to toggle)
libape 1.0.0-3
  • links: PTS
  • area: main
  • in suites: potato
  • size: 1,572 kB
  • ctags: 1,343
  • sloc: sh: 7,342; cpp: 3,418; makefile: 117
file content (1110 lines) | stat: -rw-r--r-- 33,452 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
<HTML>
<HEAD><TITLE>../doc/thread-h</TITLE></HEAD>
<BODY BGCOLOR="#ffffff">
<PRE>// Copyright (C) 1999 Open Source Telecom Corporation.
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// 
// As a special exception to the GNU General Public License, permission is 
// granted for additional uses of the text contained in its release 
// of APE.
// 
// The exception is that, if you link the APE library with other files
// to produce an executable, this does not by itself cause the
// resulting executable to be covered by the GNU General Public License.
// Your use of that executable is in no way restricted on account of
// linking the APE library code into it.
// 
// This exception does not however invalidate any other reasons why
// the executable file might be covered by the GNU General Public License.
// 
// This exception applies only to the code released under the 
// name APE.  If you copy code from other releases into a copy of
// APE, as the General Public License permits, the exception does
// not apply to the code that you add in this way.  To avoid misleading
// anyone as to the status of such modified files, you must delete
// this exception notice from them.
// 
// If you write modifications of your own for APE, it is your choice
// whether to permit this exception to apply to your modifications.
// If you do not wish that, delete this exception notice.  

#ifndef	__APE_THREAD_H__
#define	__APE_THREAD_H__
#define	__APE_POSIX

#ifndef	_REENTRANT
#define	_REENTRANT
#endif

#ifndef	_THREAD_SAFE
#define	_THREAD_SAFE
#include &lt;APE/config.h&gt;
#else
#ifndef	HAVE_CONFIG_H
#include &lt;APE/config.h&gt;
#endif
#endif

#ifndef	HAVE_PTHREAD_H
#include &lt;pthread.h&gt;
#include &lt;semaphore.h&gt;
#endif

#ifndef	__APE_MACROS_H__
#include &lt;APE/macros.h&gt;
#endif

#include &lt;time.h&gt;
#include &lt;signal.h&gt;
#include &lt;setjmp.h&gt;

#ifdef	__linux__
#define _APE_THREAD_STOPCONT
#define	_APE_THREAD_ALARM
#endif

typedef	pthread_t	tid_t;
typedef	unsigned long	timeout_t;
typedef	int		signo_t;

#define	ENTER_CRITICAL	EnterMutex();
#define	LEAVE_CRITICAL	LeaveMutex();
#define	ENTER_DEFERRED	setCancel(THREAD_CANCEL_DEFERRED);
#define LEAVE_DEFERRED 	setCancel(THREAD_CANCEL_IMMEDIATE);

// These macros override common functions with thread-safe versions. In
// particular the common &quot;libc&quot; sleep() has problems since it normally
// uses SIGARLM (as actually defined by &quot;posix&quot;).  The pthread_delay and
// usleep found in libpthread are gaurenteed not to use SIGALRM and offer
// higher resolution.  psleep() is defined to call the old process sleep.

#define	sleep(x)	ape_sleep((x) * 1000)
#define	yield()		ape_yield()
#define	psleep(x)	(sleep)(x)

enum
{
	THREAD_CANCEL_INITIAL=0,
	THREAD_CANCEL_DEFERRED=1,
	THREAD_CANCEL_IMMEDIATE,
	THREAD_CANCEL_DISABLED,
	THREAD_CANCEL_DEFAULT=THREAD_CANCEL_DEFERRED
};

enum
{
	THREAD_SUSPEND_ENABLE,
        THREAD_SUSPEND_DISABLE
};

#define	 THREAD_SIGNAL_BLOCKED	false
#define	 THREAD_SIGNAL_UNBLOCK	true
	
#ifdef	_APE_THREAD_STOPCONT
#define _SIG_THREAD_SUSPEND SIGSTOP
#define _SIG_THREAD_RESUME  SIGCONT
#else
#ifndef	SIGUSR3
#ifdef	SIGWINCH
#define	SIGUSR3	SIGWINCH
#else
#define	SIGUSR3	SIGINT
#endif
#endif
#define	_SIG_THREAD_SUSPEND SIGUSR3
#define _SIG_THREAD_RESUME SIGUSR3
#endif

class <a href="Thread.html">Thread</a>;

Thread *getAPE(void);

/**
 * The Mutex class is used to protect a section of code so that at any
 * given time only a single thread can perform the protected operation.
 * The APE Mutex is always recursive in that if the same thread invokes
 * the same mutex lock multiple times, it must release it multiple times.
 * This allows a function to call another function which also happens to
 * use the same mutex lock when called directly.
 * 
 * The Mutex can be used as a base class to protect access in a derived
 * class.  When used in this manner, the ENTER_CRITICAL and LEAVE_CRITICAL
 * macros can be used to specify when code written for the derived class
 * needs to be protected by the default Mutex of the derived class, and
 * hence is presumed to be 'thread safe' from multiple instance execution.
 * 
 * @author David Sugar &lt;dyfet@ostel.com&gt;
 * @short Mutex lock for protected access.
 */
class <a href="Mutex.html">Mutex</a> 
{
private:
#ifndef	PTHREAD_MUTEXTYPE_RECURSIVE
	int _level;
#endif

protected:
	/**
	 * Pthread mutex object.  This is protected rather than private
	 * because some mixed mode pthread operations require a mutex as
	 * well as their primary pthread object.  A good example of this
	 * is the Event class, as waiting on a conditional object must be
	 * associated with an accessable mutex.  An alternative would be
	 * to make such classes &quot;friend&quot; classes of the Mutex.
	 */
	pthread_mutex_t	_mutex;

public:
	/**
	 * The mutex is always initialized as a recursive entity.
	 */
	Mutex();

	/**
	 * Destroying the mutex removes any system resources associated
	 * with it.  If a mutex lock is currently in place, it is presumed
	 * to terminate when the Mutex is destroyed.
	 */
	~Mutex()
		{pthread_mutex_destroy(&_mutex);};

	/**
	 * Entering a Mutex locks the mutex for the current thread.  This
	 * also can be done using the ENTER_CRITICAL macro or by using the
	 * ++ operator on a mutex.
	 * 
	 * @see #LeaveMutex
	 */
#ifdef	PTHREAD_MUTEXTYPE_RECURSIVE
	inline void EnterMutex(void)
		{pthread_mutex_lock(&_mutex);};
#else
	void	EnterMutex(void);
#endif

	/**
	 * Leaving a mutex frees that mutex for use by another thread.  If
	 * the mutex has been entered (invoked) multiple times (recursivily)
	 * by the same thread, then it will need to be exited the same number
	 * of instances before it is free for re-use.  This operation can
	 * also be done using the LEAVE_CRITICAL macro or by the -- operator
	 * on a mutex.
	 * 
	 * @see #EnterMutex
	 */
#ifdef	PTHREAD_MUTEXTYPE_RECURSIVE
	inline void LeaveMutex(void)
		{pthread_mutex_unlock(&_mutex);};
#else
	void LeaveMutex(void);
#endif
};

/**
 * The Mutex Counter is a counter variable which can safely be incremented
 * or decremented by multiple threads.  A Mutex is used to protect access
 * to the counter variable (an integer).  An initial value can be specified 
 * for the counter, and it can be manipulated with the ++ and -- operators.
 * 
 * @author David Sugar &lt;dyfet@ostel.com&gt;
 * @short Thread protected integer counter.
 */
class	<a href="<a href="Mutex.html">Mutex</a>Counter.html"><a href="Mutex.html">Mutex</a>Counter</a> : public <a href="Mutex.html">Mutex</a>
{
private:
	int	counter;

public:
	MutexCounter(int initial = 0);
	
	friend int operator ++(MutexCounter &mc);
	friend int operator --(MutexCounter &mc);
};
/**
 * A semaphore is generally used as a synchronization object between multiple
 * threads or to protect a limited and finite resource such as a memory or
 * thread pool.  The semaphore has a counter which only permits access by
 * one or more threads when the value of the semaphore is non-zero.  Each
 * access reduces the current value of the semaphore by 1.  One or more
 * threads can wait on a semaphore until it is no longer 0, and hence the
 * semaphore can be used as a simple thread synchronization object to enable
 * one thread to pause others until the thread is ready or has provided data
 * for them.
 * 
 * @author David Sugar &lt;dyfet@ostel.com&gt;
 * @short Semaphore counter for thread synchronization. 
 */
class <a href="Semaphore.html">Semaphore</a>
{
protected:
	sem_t _semaphore;

public:
	/**
	 * The initial value of the semaphore can be specified.  An initial
	 * value is often used When used to lock a finite resource or to 
	 * specify the maximum number of thread instances that can access a 
	 * specified resource.
	 * 
	 * @param resource specify initial resource count or 0 default.
	 */
	Semaphore(size_t resource = 0);

	/**
	 * Destroying a semaphore also removes any system resources
	 * associated with it.  If a semaphore has threads currently waiting
	 * on it, those threads will all continue when a semaphore is
	 * destroyed.
	 */
	~Semaphore()
		{sem_destroy(&_semaphore);};

	/**
	 * Wait is used to keep a thread held until the semaphore counter
	 * is greater than 0.  If the current thread is held, then another
	 * thread must increment the semaphore.  Once the thread is accepted, 
	 * the semaphore is automatically decremented, and the thread 
	 * continues execution.
	 * 
	 * The pthread semaphore object does not support a timed &quot;wait&quot;, and
	 * hence to maintain consistancy, neither the posix nor win32 source
	 * trees support &quot;timed&quot; semaphore objects.
	 * 
	 * @see #Post
	 */
	inline void Wait(void)
		{sem_wait(&_semaphore);};
	        
	/**
	 * Posting to a semaphore increments its current value and releases
	 * the first thread waiting for the semaphore if it is currently at
	 * 0.  Interestingly, there is no support to increment a semaphore by
	 * any value greater than 1 to release multiple waiting threads in
	 * either pthread or the win32 API.  Hence, if one wants to release
	 * a semaphore to enable multiple threads to execute, one must perform
	 * multiple post operations.
	 * 
	 * @see #Wait
	 */
	inline void Post(void)
		{sem_post(&_semaphore);};
};

/**
 * The APE Event class implements a feature originally found in the WIN32 API;
 * event notification.  A target thread waits on a resetable Event, and one
 * or more other threads can then signal the waiting thread to resume 
 * execution.  A timeout can be used to specify a wait duration in 
 * milliseconds.  The Event class must be reset before it can be used again 
 * as a trigger.
 * 
 * @author: David Sugar &lt;dyfet@ostel.com&gt;
 * @short Thread synchornization on event notification.
 */
class <a href="Event.html">Event</a> : public <a href="Mutex.html">Mutex</a>
{
protected:
	pthread_cond_t _cond;
	bool _signaled;
	int _count;

public:
	Event();

	~Event()
		{pthread_cond_destroy(&_cond);};
	
	/**
	 * Once signaled, the Event class must be &quot;reset&quot; before responding
	 * to a new signal.
	 * 
	 * @see #Signal
	 */
	void Reset(void)
		{_signaled = false;};

	/**
	 * Signal the event for the waiting thread.
	 */
	void Signal(void);
	/**
	 * Wait either for the event to be signaled by another thread or
	 * for the specified timeout duration.
	 * 
	 * @see #Signal
	 * @return true if signaled, false if timed out.
	 * @param timer timeout in milliseconds to wait for a signal.
	 */
	bool Wait(timeout_t timer = 0);
};

/**
 * The buffer class represents an IPC service that is built upon a buffer
 * of fixed capacity that can be used to transfer objects between one or
 * more producer and consumer threads.  Producer threads post objects
 * into the buffer, and consumer threads wait for and receive objects from
 * the buffer.  Semaphores are used to to block the buffer from overflowing
 * and indicate when there is data available, and mutexes are used to protect
 * multiple consumers and producer threads from stepping over each other.
 * 
 * The buffer class is an abstract class in that the actual data being
 * buffered is not directly specified within the buffer class itself.  The
 * buffer class should be used as a base class for a class that actually
 * impliments buffering and which may be aware of the data types actually
 * are being buffered.  A template class could be created based on buffer
 * for this purpose.  Another possibility is to create a class derived
 * from both Thread and Buffer which can be used to implement message passing
 * threads.
 * 
 * @author David Sugar &lt;dyfet@ostel.com&gt;
 * @short Producer/Consumer buffer for use between threads.
 */
class <a href="Buffer.html">Buffer</a>
{
private:
	Mutex lock_head, lock_tail;
	Semaphore size_head, size_tail;
	size_t _size;
	size_t _used;

protected:
	/**
	 * Invoke derived class buffer peeking method.
	 * @return size of object found.
	 * @param buf pointer to copy contents of head of buffer to.
	 */
	virtual int OnPeek(void *buf) = 0;
	/**
	 * Invoke derived class object request from buffer.
	 * @return size of object returned.
	 * @param buf pointer to hold object returned from the buffer.
	 */
	virtual int OnWait(void *buf) = 0;
	/**
	 * Invoke derived class posting of object to buffer.
	 * @return size of object posted.
	 * @param buf pointer to object being posted to the buffer.
	 */
	virtual int OnPost(void *buf) = 0;

public:
	/**
	 * Create a buffer object of known capacity.
	 * @param capcity is the integer capacity of the buffer.
	 */
	Buffer(size_t capacity);
	/**
	 * In derived functions, may be used to free the actual memory
	 * used to hold buffered data.
	 */
	virtual ~Buffer()
		{return;};

	/**
	 * Return the capacity of the buffer as specified at creation.
	 * @return size of buffer.
	 */
	inline size_t getSize(void)
		{return _size;};
	
	/**
	 * Return the current capacity in use for the buffer.  Free space
	 * is technically getSize() - getUsed().
	 * @return integer used capacity of the buffer.
	 * @see #getSize
	 */
	inline size_t getUsed(void)
		{return _used;};

	/**
	 * Let one or more threads wait for an object to become available
	 * in the buffer.  The waiting thread(s) will wait forever if no
	 * object is ever placed into the buffer.
	 * 
	 * @return size of object passed by buffer in bytes.
	 * @param buf pointer to store object retrieved from the buffer.
	 */
	int Wait(void *buf);
	/**
	 * Post an object into the buffer and enable a waiting thread to
	 * receive it.
	 * 
	 * @return size of object posted in bytes.
	 * @param buf pointer to object to store in the buffer.
	 */
	int Post(void *buf);
	/**
	 * Peek at the current content (first object) in the buffer.
	 * 
	 * @return size of object in the buffer.
	 * @param buf pointer to store object found in the buffer.
	 */
	int Peek(void *buf);
};

/**
 * A buffer class that holds a known capacity of fixed sized objects defined
 * during creation.
 * 
 * @author David Sugar &lt;dyfet@ostel.com&gt;.
 * @short producer/consumer buffer for fixed size objects.
 */
class <a href="Fixed<a href="Buffer.html">Buffer</a>.html">Fixed<a href="Buffer.html">Buffer</a></a> : public <a href="Buffer.html">Buffer</a>
{
private:
	char *buf, *head, *tail;
	size_t objsize;

protected:
	/**
	 * Return the first object in the buffer.
	 * @return predefined size of this buffers objects.
	 * @param buf pointer to copy contents of head of buffer to.
	 */
	int OnPeek(void *buf);
	/**
	 * Wait for and return a fixed object in the buffer.
	 * @return predefined size of this buffers objects.
	 * @param buf pointer to hold object returned from the buffer.
	 */
	int OnWait(void *buf);
	/**
	 * Post an object of the appropriate size into the buffer.
	 * @return predefined size of this buffers objects.
	 * @param buf pointer to data to copy into the buffer.
	 */
	int OnPost(void *buf);	

public:
	/**
	 * Create a buffer of known capacity for objects of a specified
	 * size.
	 * 
	 * @param capacity of the buffer.
	 * @param objsize for each object held in the buffer.
	 */
	FixedBuffer(size_t capacity, size_t objsize);
	/**
	 * Create a copy of an existing fixed size buffer and duplicate
	 * it's contents.
	 * 
	 * @param fb existing FixedBuffer object.
	 */
	FixedBuffer(const FixedBuffer &fb);
	/**
	 * Destroy the fixed buffer and free the memory used to store objects.
	 */
	~FixedBuffer();

	FixedBuffer &operator=(const FixedBuffer &fb);
};

/**
 * The Pipe uses system kernel buffering to hold data being passed either
 * between two execution contexts within the same process, or between
 * different processes.  Unlike Buffer, Pipe uses system descriptors and
 * kernel memory.  Under Posix, the size of the pipe and associated kernel
 * memory is always a fixed constant as defined by _PC_PIPE_BUF.  Since
 * the pipe does not deal with fixed objects, any data can be read from or
 * written to the kernel pipe buffer.
 * 
 * @author David Sugar &lt;dyfet@ostel.com&gt;.
 * @short kernel buffering between processes and/or threads.
 */
class <a href="Pipe.html">Pipe</a>
{
private:
	int fd[2];

protected:
	/**
	 * Sender is often used for implementing a fork()'d message port
	 * between processes.  By defining the current pipe as only used
	 * for sending, the receiver is presumed to be in the other half
	 * of a fork()'d process.
	 * 
	 * @see #Receiver
	 */
	inline void Sender(void)
		{close(fd[0]);};
	/**
	 * Receiver is often used for implementing a fork()'d message port
	 * between processes.  By defining the current pipe as only used
	 * for receiving, the sender is presumed to be in the other half
	 * of a fork()'d process.
	 * 
	 * @see #Sender
	 */
	inline void Receiver(void)
		{close(fd[1]);};

public:
	/**
	 * Create a kernel pipe descriptor set using pipe().
	 */
	Pipe();
	/**
	 * Destroy the pipe and kernel descriptor resources.
	 */
	~Pipe();
	/**
	 * Create a pipe as a duplicate of an existing pipe.
	 * 
	 * @param orig pipe to duplicate.
	 */
	Pipe(const Pipe &orig);

	Pipe &operator=(const Pipe &orig);
	
	/**
	 * Read an arbitrary number of bytes from the pipe buffer.
	 * 
	 * @return number of bytes actually read if successful.
	 * @param addr pointer to store read data.
	 * @param len number of bytes to read.
	 */
	inline int Read(void *addr, size_t len)
		{return read(fd[0], (char *)addr, len);};

	/**
	 * Write an arbitrary number of butes to the pipe buffer.
	 * 
	 * @return number of bytes read if successful.
	 * @param addr pointer to write data from.
	 * @param len number of butes to write.
	 */
	inline int Write(void *addr, size_t len)
		{return write(fd[1], (char *)addr, len);};

	friend inline int read(Pipe &p, void *addr, size_t len)
		{return read(p.fd[0], (char *)addr, len);};

	friend inline int write(Pipe &p, void *addr, size_t len)
		{return write(p.fd[1], (char *)addr, len);};
};

/**
 * Every thread of execution in an APE application is created by deriving
 * a unique class from the APE Thread class and by implementing the Run
 * method.  The base Thread class supports encapsulation of the generic
 * APE threading methods implemented on various target operating systems.  
 * This includes the ability to start and stop threads in a synchronized
 * and controllable manner, the ability to specify thread execution priority,
 * and thread specific &quot;system call&quot; wrappers, such as for sleep and yield.
 * A thread exception is thrown if the thread cannot be created.
 * 
 * @author David Sugar &lt;dyfet@tycho.com&gt;
 * @short base class used to derive all APE threads of execution.
 */
class <a href="Thread.html">Thread</a>
{
private:
	static Thread *_main;

#ifndef	_APE_THREAD_ALARM
	static Thread *_timer;
	static Mutex _arm;
#endif
	
	Thread *_parent;
	pthread_t _tid;
	pthread_attr_t _attr;
	int	_cancel;
	jmp_buf	_env;
	time_t	_alarm;
	Semaphore *_start;

	static	void Execute(Thread *th);
	static	void SignalHandler(int signo);

protected:
       	/**
	 * All APE threads execute by deriving the Run method of Thread.
	 * This method is called after Initial to begin normal operation
	 * of the thread.  If the method terminates, then the thread will
	 * also terminate after notifying it's parent and calling it's
	 * Final() method.
	 * 
	 * @see #Initial
	 */
	virtual void Run(void) = 0;

	/**
	 * This method is called for the very first instance of a new thread
	 * being created in a multi-threaded application.  Hence, it is only
	 * called once, and by the derived Thread class that happens to be
	 * created first.
	 */
	virtual void First(void)
		{return;};
	
	/**
	 * A thread that is self terminating, either by invoking Exit() or
	 * leaving it's Run(), will have this method called.  It can be used
	 * to self delete the current object assuming the object was created
	 * with new on the heap rather than stack local, hence one may often
	 * see Final defined as &quot;delete this&quot; in a derived thread class.  A
	 * Final method, while running, cannot be terminated or cancelled by
	 * another thread.
	 * 
	 * @see #Exit
	 * @see #Run
	 */
	virtual void Final(void)
		{return;};

	/**
	 * The initial method is called by a newly created thread when it
	 * starts execution.  This method is ran with deferred cancellation
	 * disabled by default.  The Initial method is given a seperate
	 * handler so that it can create temporary objects on it's own
	 * stack frame, rather than having objects created on Run() that
	 * are only needed by startup and yet continue to consume stack space.
	 * 
	 * @see #Run
	 */
	virtual void Initial(void)
		{return;};
	
	/**
	 * Since getParent() and getAPE() only refer to an object of the
	 * Thread &quot;base&quot; type, this virtual method can be replaced in a
	 * derived class with something that returns data specific to the
	 * derived class that can still be accessed through the pointer
	 * returned by getParent() and getAPE().
	 *
	 * @return pointer to derived class specific data.
	 */
	virtual void *getExtended(void)
		{return NULL;};

	/**
	 * When a thread terminates, it now sends a notification message
	 * to the parent thread which created it.  The actual use of this
	 * notification is left to be defined in a derived class.
	 * 
	 * @param th the thread that has terminated.
	 */
	virtual void Notify(Thread *th)
		{return;};

	/**
	 * In the Posix version of APE, this can be used to send a
	 * signal into the parent thread of the current object.
	 * 
	 * @param signo a posix signal id.
	 */
	inline void SignalParent(signo_t signo)
		{_parent-&gt;SignalThread(signo);};

	/**
	 * In the Posix version of APE, this can be used to send a
	 * signal into the nain application thread.
	 * 
	 * @param signo a posix signal id.
	 */
	inline void SignalMain(signo_t signo)
		{_main-&gt;SignalThread(signo);};

	/**
	 * A derivable method to call when a SIGALRM is being delivered
	 * to a specific thread.
	 */
	virtual void OnTimer(void)
		{return;};

	/**
	 * A derived method to handle asynchronous I/O requests delivered
	 * to the specified thread.
	 */
	virtual void OnPolling(void)
		{return;};

	/**
	 * A derivable method to call for delivering a signal event to
	 * a specified thread.
	 *
	 * @param signo posix signal id.
	 */
	virtual void OnSignal(int signo)
		{return;};

	/**
	 * A thread-safe sleep call.  On most Posix systems, &quot;sleep()&quot;
	 * is implimented with SIGALRM making it unusable from multipe
	 * threads.  Pthread libraries often define an alternate &quot;sleep&quot;
	 * handler such as usleep(), nanosleep(), or nap(), that is thread
	 * safe, and also offers a higher timer resolution.
	 * 
	 * @param msec timeout in milliseconds.
	 */
	inline void Sleep(timeout_t msec)
		{ape_sleep(msec);};

	/**
	 * Used to properly exit from a Thread derived Run() or Initial()
	 * method.  Terminates execution of the current thread and calls
	 * the derived classes Final() method.
	 */
	inline void Exit(void)
		{longjmp(_env, 1);};
	       
	/**
	 * Used to specify a timeout event that can be delivered to the
	 * current thread via SIGALRM.  When the timer expires, the OnTimer() 
	 * method is called for the thread.  At present, only one thread
	 * timer can be active at any given time.  On some operating
	 * systems (including Linux) a timer can be active on each thread.
	 * 
	 * @param timer timeout in milliseconds.
	 */
	void setTimer(timeout_t timer);
	/**
	 * Gets the time remaining for the current threads timer before
	 * it expires.
	 * 
	 * @return time remaining before timer expires in milliseconds.
	 */
	timeout_t getTimer(void);
	/**
	 * Terminates the timer before the timeout period has expired.
	 * This prevents the timer from sending it's SIGALRM and makes
	 * the timer available to other threads.
	 */
	void endTimer(void);
	/**
	 * Used to wait on a Posix signal from another thread.  This can be
	 * used as a crude rondevious/synchronization method between threads.
	 * 
	 * @param signo a posix signal id.
	 */
	void WaitSignal(signo_t signo);
	/**
	 * Yeilds the current thread's CPU time slice to allow another thread to
	 * begin immediate execution.
	 */
	void Yield(void);
	/**
	 * Sets thread cancellation mode.  Threads can either be set immune to
	 * termination (THREAD_CANCEL_DISABLED), can be set to terminate when
	 * reaching specific &quot;thread cancellation points&quot; (THREAD_CANCEL_DEFERRED)
	 * or immediately when Terminate is requested (THREAD_CANCEL_IMMEDIATE).
	 * 
	 * @param mode for cancellation of the current thread.
	 */
	void setCancel(int mode);
	/**
	 * Sets the thread's ability to be suspended from execution.  The
	 * thread may either have suspend enabled (THREAD_SUSPEND_ENABLE) or
	 * disabled (THREAD_SUSPEND_DISABLE).
	 * 
	 * @param mode for suspend.
	 */
	void setSuspend(int mode);
	/**
	 * Used to enable or disable a signal within the current thread.
	 *
	 * @param signo posix signal id.
	 * @param active set to true to enable.
	 */
	void setSignal(int signo, bool mode);
	/**
	 * Used by another thread to terminate the current thread.  Termination
	 * actually occurs based on the current setCancel() mode.  When the
	 * current thread does terminate, control is returned to the requesting
	 * thread.  Terminate() should always be called at the start of any
	 * destructor of a class derived from Thread to assure the remaining
	 * part of the destructor is called without the thread still executing.
	 */
	void Terminate(void);
public:
	/**
	 * This is actually a special constructor that is used to create a
	 * thread &quot;object&quot; for the current execution context when that context
	 * is not created via an instance of a derived Thread object itself.
	 * This constructor does not support First.
	 * 
	 * @param bool used if the main &quot;thread&quot; of the application.
	 */
	Thread(bool flag);
	/**
	 * When a thread object is contructed, a new thread of execution
	 * context is created.  This constructor allows basic properties
	 * of that context (thread priority, stack space, etc) to be defined.
	 * The starting condition is also specified for whether the thread
	 * is to wait on a semaphore before begining execution or wait until
	 * it's start method is called.
	 * 
	 * @param start semaphore to wait before executing thread.
	 * @param pri thread base priority relative to it's parent.
	 * @param stack space as needed in some implementations.
	 */
	Thread(Semaphore *start = NULL, int pri = 0, size_t stack = 0);
	/**
	 * A thread of execution can also be specified by cloning an existing
	 * thread.  The existing thread's properties (cancel mode, priority,
	 * etc), are also duplicated.
	 * 
	 * @param th currently executing thread object to clone.
	 */
	Thread(const Thread &th);
	/**
	 * The thread destructor should clear up any resources that have
	 * been allocated by the thread.  The desctructor of a derived
	 * thread should begin with Terminate() and is presumed to then
	 * execute within the context of the thread causing terminaton.
	 */
	virtual ~Thread()
		{Terminate();};
	
	/**
	 * When a new thread is created, it does not begin immediate
	 * execution.  This is because the derived class virtual tables
	 * are not properly loaded at the time the C++ object is created
	 * within the constructor itself, at least in some compiler/system 
	 * combinations.  The thread can either be told to wait for an
	 * external semaphore, or it can be started directly after the
	 * constructor completes by calling the Start() method.
	 * 
	 * @return error code if execution fails.
	 * @param start optional starting semaphore to alternately use.
	 */
	int Start(Semaphore *start = NULL);

	/**
	 * Gets the pointer to the Thread class which created the current
	 * thread object.
	 * 
	 * @return a Thread *, or &quot;(Thread *)this&quot; if no parent.
	 */
	inline Thread *getParent(void)
		{return _parent;};
		
	/**
	 * Delivers a Posix signal to the current thread.
	 * 
	 * @param signo a posix signal id.
	 */
	inline void SignalThread(int signo)
		{pthread_kill(_tid, signo);};

	/**
	 * Suspends execution of the selected thread.  Pthreads do not
	 * normally support suspendable threads, so the behavior is
	 * simulated with signals.  On systems such as Linux that
	 * define threads as processes, SIGSTOP and SIGCONT may be used.
	 */
#ifdef _THR_SUNOS5
	inline void Suspend(void)
		{thr_suspend((thread_t)_tid);};
#else
	inline void Suspend(void)
		{pthread_kill(_tid, _SIG_THREAD_SUSPEND);};
#endif

	/**
	 * Resumes execution of the selected thread.
	 */
#ifdef	_THR_SUNOS5
	inline void Resume(void)
		{thr_continue((thread_t)_tid);};
#else
	inline void Resume(void)
		{pthread_kill(_tid, _SIG_THREAD_RESUME);};
#endif

	/**
	 * Used to retrieve the cancellation mode in effect for the
	 * selected thread.
	 * 
	 * @return cancellation mode constant.
	 */
	inline int getCancel(void)
		{return _cancel;};

	/**
	 * Verifies if the thread is still running or has already been
	 * terminated but not yet deleted.
	 * 
	 * @return true if the thread is still executing.
	 */
	inline bool isRunning(void)
		{return _tid != 0;};

	/**
	 * Tests to see if the current execution context is the same as
	 * the specified thread object.
	 * 
	 * @return true if the current context is this object.
	 */
	inline bool isThread(void)
		{return _tid == pthread_self();};

	/**
	 * Thread safe sleep call replacement.  This is mapped into sleep().
	 * 
	 * @param msec timeout in millisecond time range.
	 */
	friend void ape_sleep(timeout_t msec);

	/**
	 * Suspend the execution of the specified thread.
	 * 
	 * @param th specified thread.
	 */
	friend void suspend(Thread &th)
		{pthread_kill(th._tid, _SIG_THREAD_SUSPEND);};

	/**
	 * Resume execution of the specified thread.
	 * 
	 * @param th specified thread.
	 */
	friend void resume(Thread &th)
		{pthread_kill(th._tid, _SIG_THREAD_RESUME);};

	/**
	 * Signal the semaphore that the specified thread is waiting for
	 * before beginning execution.
	 * 
	 * @param th specified thread.
	 */
	friend inline void operator++(Thread &th)
		{th._start-&gt;Post();};

	/**
	 * Start execution of a specified thread.
	 */
	friend inline int start(Thread &th, Semaphore *start)
		{return th.Start(start);};

	/**
	 * Install a signal handler for use by APE threads and
	 * the OnSignal() event notification handler.
	 *
	 * @param signo posix signal id.
	 */

	friend void siginstall(int signo);
};

/**
 * This class allows the creation of a thread context unique &quot;pointer&quot;
 * that can be set and retrieved and can be used to create thread specific
 * data areas for implementing &quot;thread safe&quot; library routines.
 * 
 * @author David Sugar &lt;dyfet@ostel.com&gt;
 * @short container for thread specific data storage.
 */
class <a href="ThreadKey.html">ThreadKey</a>
{
private:
	pthread_key_t key;

public:
	/**
	 * Create a unique thread specific container.
	 */
	ThreadKey();
	/**
	 * Destroy a thread specific container and any contents reserved.
	 */
	~ThreadKey();
	/**
	 * Get the value of the pointer for the thread specific data
	 * container.  A unique pointer can be set for each execution
	 * context.
	 * 
	 * @return a unique void * for each execution context.
	 */
	void *getKey(void);
	/**
	 * Set the value of the pointer for the current thread specific
	 * execution context.  This can be used to store thread context
	 * specific data.
	 * 
	 * @param ptr to thread context specific data.
	 */
	void setKey(void *);
};

inline void *getKey(ThreadKey &tk)
	{return tk.getKey();};

inline void setKey(ThreadKey &tk, void *ptr)
	{tk.setKey(ptr);};

inline void operator ++(Mutex &m)
	{m.EnterMutex();};
		
inline void operator --(Mutex &m)
	{m.LeaveMutex();};

inline void operator ++(Semaphore &s)
	{s.Post();};

inline void operator --(Semaphore &s)
	{s.Wait();};

inline void operator ++(Event &s)
	{s.Signal();};

inline void operator --(Event &s)
	{s.Wait();};

inline void signal(Thread &th, int signo)
	{th.SignalThread(signo);};

inline void signal(Event &ev)
	{ev.Signal();};

inline void signal(Semaphore &sem)
	{sem.Post();};

inline void wait(Semaphore &sem)
	{sem.Wait();};

inline void wait(Event &ev, timeout_t timer)
	{ev.Wait(timer);};

inline void reset(Event &ev)
	{ev.Reset();};

inline int get(Buffer &b, void *o)
	{return b.Wait(o);};

inline int put(Buffer &b, void *o)
	{return b.Post(o);};

inline int peek(Buffer &b, void *o)
	{return b.Peek(o);};

int operator++(MutexCounter &mc);
int operator--(MutexCounter &mc);

struct	timespec *gettimeout(struct timespec *spec, timeout_t timeout);	
void	ape_sleep(timeout_t msec);
void	ape_yield(void);
void	wait(signo_t signo);
void	pdetach(void);
#endif

</PRE>
<HR>
<address>Documentation generated by dyfet@home.sys on Thu Dec 16 09:54:26 EST 1999
</address>
</BODY>
</HTML>