summaryrefslogtreecommitdiff
path: root/pjlib/include/pj/os.h
blob: d57d13b65c492d5fcfc2edd3b9b9622bb8930736 (plain)
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
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
/* $Id$ */
/* 
 * Copyright (C)2003-2006 Benny Prijono <benny@prijono.org>
 *
 * 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 
 */
#ifndef __PJ_OS_H__
#define __PJ_OS_H__

/**
 * @file os.h
 * @brief OS dependent functions
 */
#include <pj/types.h>

PJ_BEGIN_DECL

/**
 * @defgroup PJ_OS Operating System Dependent Functionality.
 * @ingroup PJ
 */


/* **************************************************************************/
/**
 * @defgroup PJ_THREAD Threads
 * @ingroup PJ_OS
 * @{
 * This module provides multithreading API.
 *
 * \section pj_thread_examples_sec Examples
 *
 * For examples, please see:
 *  - \ref page_pjlib_thread_test
 *  - \ref page_pjlib_sleep_test
 *
 */

/**
 * Thread creation flags:
 * - PJ_THREAD_SUSPENDED: specify that the thread should be created suspended.
 */
typedef enum pj_thread_create_flags
{
    PJ_THREAD_SUSPENDED = 1
} pj_thread_create_flags;


/**
 * Type of thread entry function.
 */
typedef int (PJ_THREAD_FUNC pj_thread_proc)(void*);

/**
 * Size of thread struct.
 */
#if !defined(PJ_THREAD_DESC_SIZE)
#   define PJ_THREAD_DESC_SIZE	    (64)
#endif

/**
 * Thread structure, to thread's state when the thread is created by external
 * or native API. 
 */
typedef long pj_thread_desc[PJ_THREAD_DESC_SIZE];

/**
 * Get process ID.
 * @return process ID.
 */
PJ_DECL(pj_uint32_t) pj_getpid(void);

/**
 * Create a new thread.
 *
 * @param pool          The memory pool from which the thread record 
 *                      will be allocated from.
 * @param thread_name   The optional name to be assigned to the thread.
 * @param proc          Thread entry function.
 * @param arg           Argument to be passed to the thread entry function.
 * @param stack_size    The size of the stack for the new thread, or ZERO or
 *                      PJ_THREAD_DEFAULT_STACK_SIZE to let the 
 *		        library choose the reasonable size for the stack. 
 *                      For some systems, the stack will be allocated from 
 *                      the pool, so the pool must have suitable capacity.
 * @param flags         Flags for thread creation, which is bitmask combination 
 *                      from enum pj_thread_create_flags.
 * @param thread        Pointer to hold the newly created thread.
 *
 * @return	        PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_thread_create(  pj_pool_t *pool, 
                                        const char *thread_name,
				        pj_thread_proc *proc, 
                                        void *arg,
				        pj_size_t stack_size, 
                                        unsigned flags,
					pj_thread_t **thread );

/**
 * Register a thread that was created by external or native API to PJLIB.
 * This function must be called in the context of the thread being registered.
 * When the thread is created by external function or API call,
 * it must be 'registered' to PJLIB using pj_thread_register(), so that it can
 * cooperate with PJLIB's framework. During registration, some data needs to
 * be maintained, and this data must remain available during the thread's 
 * lifetime.
 *
 * @param thread_name   The optional name to be assigned to the thread.
 * @param desc          Thread descriptor, which must be available throughout 
 *                      the lifetime of the thread.
 * @param thread        Pointer to hold the created thread handle.
 *
 * @return              PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_thread_register ( const char *thread_name,
					  pj_thread_desc desc,
					  pj_thread_t **thread);

/**
 * Check if this thread has been registered to PJLIB.
 *
 * @return		Non-zero if it is registered.
 */
PJ_DECL(pj_bool_t) pj_thread_is_registered(void);


/**
 * Get thread name.
 *
 * @param thread    The thread handle.
 *
 * @return Thread name as null terminated string.
 */
PJ_DECL(const char*) pj_thread_get_name(pj_thread_t *thread);

/**
 * Resume a suspended thread.
 *
 * @param thread    The thread handle.
 *
 * @return zero on success.
 */
PJ_DECL(pj_status_t) pj_thread_resume(pj_thread_t *thread);

/**
 * Get the current thread.
 *
 * @return Thread handle of current thread.
 */
PJ_DECL(pj_thread_t*) pj_thread_this(void);

/**
 * Join thread, and block the caller thread until the specified thread exits.
 * If the specified thread has already been dead, or it does not exist,
 * the function will return immediately with successfull status.
 *
 * @param thread    The thread handle.
 *
 * @return PJ_SUCCESS on success.
 */
PJ_DECL(pj_status_t) pj_thread_join(pj_thread_t *thread);


/**
 * Destroy thread and release resources allocated for the thread.
 * However, the memory allocated for the pj_thread_t itself will only be released
 * when the pool used to create the thread is destroyed.
 *
 * @param thread    The thread handle.
 *
 * @return zero on success.
 */
PJ_DECL(pj_status_t) pj_thread_destroy(pj_thread_t *thread);


/**
 * Put the current thread to sleep for the specified miliseconds.
 *
 * @param msec Miliseconds delay.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_thread_sleep(unsigned msec);

/**
 * @def PJ_CHECK_STACK()
 * PJ_CHECK_STACK() macro is used to check the sanity of the stack.
 * The OS implementation may check that no stack overflow occurs, and
 * it also may collect statistic about stack usage.
 */
#if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0

#  define PJ_CHECK_STACK() pj_thread_check_stack(__FILE__, __LINE__)

/** @internal
 * The implementation of stack checking. 
 */
PJ_DECL(void) pj_thread_check_stack(const char *file, int line);

/** @internal
 * Get maximum stack usage statistic. 
 */
PJ_DECL(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread);

/** @internal
 * Dump thread stack status. 
 */
PJ_DECL(pj_status_t) pj_thread_get_stack_info(pj_thread_t *thread,
					      const char **file,
					      int *line);
#else

#  define PJ_CHECK_STACK()
/** pj_thread_get_stack_max_usage() for the thread */
#  define pj_thread_get_stack_max_usage(thread)	    0
/** pj_thread_get_stack_info() for the thread */
#  define pj_thread_get_stack_info(thread,f,l)	    (*(f)="",*(l)=0)
#endif	/* PJ_OS_HAS_CHECK_STACK */

/**
 * @}
 */

/* **************************************************************************/
/**
 * @defgroup PJ_TLS Thread Local Storage.
 * @ingroup PJ_OS
 * @{
 */

/** 
 * Allocate thread local storage index. The initial value of the variable at
 * the index is zero.
 *
 * @param index	    Pointer to hold the return value.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_thread_local_alloc(long *index);

/**
 * Deallocate thread local variable.
 *
 * @param index	    The variable index.
 */
PJ_DECL(void) pj_thread_local_free(long index);

/**
 * Set the value of thread local variable.
 *
 * @param index	    The index of the variable.
 * @param value	    The value.
 */
PJ_DECL(pj_status_t) pj_thread_local_set(long index, void *value);

/**
 * Get the value of thread local variable.
 *
 * @param index	    The index of the variable.
 * @return	    The value.
 */
PJ_DECL(void*) pj_thread_local_get(long index);


/**
 * @}
 */


/* **************************************************************************/
/**
 * @defgroup PJ_ATOMIC Atomic Variables
 * @ingroup PJ_OS
 * @{
 *
 * This module provides API to manipulate atomic variables.
 *
 * \section pj_atomic_examples_sec Examples
 *
 * For some example codes, please see:
 *  - @ref page_pjlib_atomic_test
 */


/**
 * Create atomic variable.
 *
 * @param pool	    The pool.
 * @param initial   The initial value of the atomic variable.
 * @param atomic    Pointer to hold the atomic variable upon return.
 *
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_atomic_create( pj_pool_t *pool, 
				       pj_atomic_value_t initial,
				       pj_atomic_t **atomic );

/**
 * Destroy atomic variable.
 *
 * @param atomic_var	the atomic variable.
 *
 * @return PJ_SUCCESS if success.
 */
PJ_DECL(pj_status_t) pj_atomic_destroy( pj_atomic_t *atomic_var );

/**
 * Set the value of an atomic type, and return the previous value.
 *
 * @param atomic_var	the atomic variable.
 * @param value		value to be set to the variable.
 */
PJ_DECL(void) pj_atomic_set( pj_atomic_t *atomic_var, 
			     pj_atomic_value_t value);

/**
 * Get the value of an atomic type.
 *
 * @param atomic_var	the atomic variable.
 *
 * @return the value of the atomic variable.
 */
PJ_DECL(pj_atomic_value_t) pj_atomic_get(pj_atomic_t *atomic_var);

/**
 * Increment the value of an atomic type.
 *
 * @param atomic_var	the atomic variable.
 */
PJ_DECL(void) pj_atomic_inc(pj_atomic_t *atomic_var);

/**
 * Increment the value of an atomic type and get the result.
 *
 * @param atomic_var	the atomic variable.
 *
 * @return              The incremented value.
 */
PJ_DECL(pj_atomic_value_t) pj_atomic_inc_and_get(pj_atomic_t *atomic_var);

/**
 * Decrement the value of an atomic type.
 *
 * @param atomic_var	the atomic variable.
 */
PJ_DECL(void) pj_atomic_dec(pj_atomic_t *atomic_var);

/**
 * Decrement the value of an atomic type and get the result.
 *
 * @param atomic_var	the atomic variable.
 *
 * @return              The decremented value.
 */
PJ_DECL(pj_atomic_value_t) pj_atomic_dec_and_get(pj_atomic_t *atomic_var);

/**
 * Add a value to an atomic type.
 *
 * @param atomic_var	The atomic variable.
 * @param value		Value to be added.
 */
PJ_DECL(void) pj_atomic_add( pj_atomic_t *atomic_var,
			     pj_atomic_value_t value);

/**
 * Add a value to an atomic type and get the result.
 *
 * @param atomic_var	The atomic variable.
 * @param value		Value to be added.
 *
 * @return              The result after the addition.
 */
PJ_DECL(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var,
			                          pj_atomic_value_t value);

/**
 * @}
 */

/* **************************************************************************/
/**
 * @defgroup PJ_MUTEX Mutexes.
 * @ingroup PJ_OS
 * @{
 *
 * Mutex manipulation. Alternatively, application can use higher abstraction
 * for lock objects, which provides uniform API for all kinds of lock 
 * mechanisms, including mutex. See @ref PJ_LOCK for more information.
 */

/**
 * Mutex types:
 *  - PJ_MUTEX_DEFAULT: default mutex type, which is system dependent.
 *  - PJ_MUTEX_SIMPLE: non-recursive mutex.
 *  - PJ_MUTEX_RECURSIVE: recursive mutex.
 */
typedef enum pj_mutex_type_e
{
    PJ_MUTEX_DEFAULT,
    PJ_MUTEX_SIMPLE,
    PJ_MUTEX_RECURSE
} pj_mutex_type_e;


/**
 * Create mutex of the specified type.
 *
 * @param pool	    The pool.
 * @param name	    Name to be associated with the mutex (for debugging).
 * @param type	    The type of the mutex, of type #pj_mutex_type_e.
 * @param mutex	    Pointer to hold the returned mutex instance.
 *
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_mutex_create(pj_pool_t *pool, 
                                     const char *name,
				     int type, 
                                     pj_mutex_t **mutex);

/**
 * Create simple, non-recursive mutex.
 * This function is a simple wrapper for #pj_mutex_create to create 
 * non-recursive mutex.
 *
 * @param pool	    The pool.
 * @param name	    Mutex name.
 * @param mutex	    Pointer to hold the returned mutex instance.
 *
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, const char *name,
					     pj_mutex_t **mutex );

/**
 * Create recursive mutex.
 * This function is a simple wrapper for #pj_mutex_create to create 
 * recursive mutex.
 *
 * @param pool	    The pool.
 * @param name	    Mutex name.
 * @param mutex	    Pointer to hold the returned mutex instance.
 *
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool,
					        const char *name,
						pj_mutex_t **mutex );

/**
 * Acquire mutex lock.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex);

/**
 * Release mutex lock.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_mutex_unlock(pj_mutex_t *mutex);

/**
 * Try to acquire mutex lock.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code if the
 *		    lock couldn't be acquired.
 */
PJ_DECL(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex);

/**
 * Destroy mutex.
 *
 * @param mutex	    Te mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_mutex_destroy(pj_mutex_t *mutex);

/**
 * Determine whether calling thread is owning the mutex (only available when
 * PJ_DEBUG is set).
 * @param mutex	    The mutex.
 * @return	    Non-zero if yes.
 */
#if defined(PJ_DEBUG) && PJ_DEBUG != 0
   PJ_DECL(pj_bool_t) pj_mutex_is_locked(pj_mutex_t *mutex);
#else
#  define pj_mutex_is_locked(mutex)	    1
#endif

/**
 * @}
 */

/* **************************************************************************/
/**
 * @defgroup PJ_RW_MUTEX Reader/Writer Mutex
 * @ingroup PJ_OS
 * @{
 * Reader/writer mutex is a classic synchronization object where multiple
 * readers can acquire the mutex, but only a single writer can acquire the 
 * mutex.
 */

/**
 * Opaque declaration for reader/writer mutex.
 * Reader/writer mutex is a classic synchronization object where multiple
 * readers can acquire the mutex, but only a single writer can acquire the 
 * mutex.
 */
typedef struct pj_rwmutex_t pj_rwmutex_t;

/**
 * Create reader/writer mutex.
 *
 * @param pool	    Pool to allocate memory for the mutex.
 * @param name	    Name to be assigned to the mutex.
 * @param mutex	    Pointer to receive the newly created mutex.
 *
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_rwmutex_create(pj_pool_t *pool, const char *name,
				       pj_rwmutex_t **mutex);

/**
 * Lock the mutex for reading.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_rwmutex_lock_read(pj_rwmutex_t *mutex);

/**
 * Lock the mutex for writing.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_rwmutex_lock_write(pj_rwmutex_t *mutex);

/**
 * Release read lock.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_rwmutex_unlock_read(pj_rwmutex_t *mutex);

/**
 * Release write lock.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_rwmutex_unlock_write(pj_rwmutex_t *mutex);

/**
 * Destroy reader/writer mutex.
 *
 * @param mutex	    The mutex.
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_rwmutex_destroy(pj_rwmutex_t *mutex);


/**
 * @}
 */


/* **************************************************************************/
/**
 * @defgroup PJ_CRIT_SEC Critical sections.
 * @ingroup PJ_OS
 * @{
 * Critical section protection can be used to protect regions where:
 *  - mutual exclusion protection is needed.
 *  - it's rather too expensive to create a mutex.
 *  - the time spent in the region is very very brief.
 *
 * Critical section is a global object, and it prevents any threads from
 * entering any regions that are protected by critical section once a thread
 * is already in the section.
 *
 * Critial section is \a not recursive!
 *
 * Application <b>MUST NOT</b> call any functions that may cause current
 * thread to block (such as allocating memory, performing I/O, locking mutex,
 * etc.) while holding the critical section.
 */
/**
 * Enter critical section.
 */
PJ_DECL(void) pj_enter_critical_section(void);

/**
 * Leave critical section.
 */
PJ_DECL(void) pj_leave_critical_section(void);

/**
 * @}
 */

/* **************************************************************************/
#if defined(PJ_HAS_SEMAPHORE) && PJ_HAS_SEMAPHORE != 0
/**
 * @defgroup PJ_SEM Semaphores.
 * @ingroup PJ_OS
 * @{
 *
 * This module provides abstraction for semaphores, where available.
 */

/**
 * Create semaphore.
 *
 * @param pool	    The pool.
 * @param name	    Name to be assigned to the semaphore (for logging purpose)
 * @param initial   The initial count of the semaphore.
 * @param max	    The maximum count of the semaphore.
 * @param sem	    Pointer to hold the semaphore created.
 *
 * @return	    PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_sem_create( pj_pool_t *pool, 
                                    const char *name,
				    unsigned initial, 
                                    unsigned max,
				    pj_sem_t **sem);

/**
 * Wait for semaphore.
 *
 * @param sem	The semaphore.
 *
 * @return	PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_sem_wait(pj_sem_t *sem);

/**
 * Try wait for semaphore.
 *
 * @param sem	The semaphore.
 *
 * @return	PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_sem_trywait(pj_sem_t *sem);

/**
 * Release semaphore.
 *
 * @param sem	The semaphore.
 *
 * @return	PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_sem_post(pj_sem_t *sem);

/**
 * Destroy semaphore.
 *
 * @param sem	The semaphore.
 *
 * @return	PJ_SUCCESS on success, or the error code.
 */
PJ_DECL(pj_status_t) pj_sem_destroy(pj_sem_t *sem);

/**
 * @}
 */
#endif	/* PJ_HAS_SEMAPHORE */


/* **************************************************************************/
#if defined(PJ_HAS_EVENT_OBJ) && PJ_HAS_EVENT_OBJ != 0
/**
 * @defgroup PJ_EVENT Event Object.
 * @ingroup PJ_OS
 * @{
 *
 * This module provides abstraction to event object (e.g. Win32 Event) where
 * available. Event objects can be used for synchronization among threads.
 */

/**
 * Create event object.
 *
 * @param pool		The pool.
 * @param name		The name of the event object (for logging purpose).
 * @param manual_reset	Specify whether the event is manual-reset
 * @param initial	Specify the initial state of the event object.
 * @param event		Pointer to hold the returned event object.
 *
 * @return event handle, or NULL if failed.
 */
PJ_DECL(pj_status_t) pj_event_create(pj_pool_t *pool, const char *name,
				     pj_bool_t manual_reset, pj_bool_t initial,
				     pj_event_t **event);

/**
 * Wait for event to be signaled.
 *
 * @param event	    The event object.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_event_wait(pj_event_t *event);

/**
 * Try wait for event object to be signalled.
 *
 * @param event The event object.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_event_trywait(pj_event_t *event);

/**
 * Set the event object state to signaled. For auto-reset event, this 
 * will only release the first thread that are waiting on the event. For
 * manual reset event, the state remains signaled until the event is reset.
 * If there is no thread waiting on the event, the event object state 
 * remains signaled.
 *
 * @param event	    The event object.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_event_set(pj_event_t *event);

/**
 * Set the event object to signaled state to release appropriate number of
 * waiting threads and then reset the event object to non-signaled. For
 * manual-reset event, this function will release all waiting threads. For
 * auto-reset event, this function will only release one waiting thread.
 *
 * @param event	    The event object.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_event_pulse(pj_event_t *event);

/**
 * Set the event object state to non-signaled.
 *
 * @param event	    The event object.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_event_reset(pj_event_t *event);

/**
 * Destroy the event object.
 *
 * @param event	    The event object.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_event_destroy(pj_event_t *event);

/**
 * @}
 */
#endif	/* PJ_HAS_EVENT_OBJ */

/* **************************************************************************/
/**
 * @addtogroup PJ_TIME Time Data Type and Manipulation.
 * @ingroup PJ_OS
 * @{
 * This module provides API for manipulating time.
 *
 * \section pj_time_examples_sec Examples
 *
 * For examples, please see:
 *  - \ref page_pjlib_sleep_test
 */

/**
 * Get current time of day in local representation.
 *
 * @param tv	Variable to store the result.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_gettimeofday(pj_time_val *tv);


/**
 * Parse time value into date/time representation.
 *
 * @param tv	The time.
 * @param pt	Variable to store the date time result.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_time_decode(const pj_time_val *tv, pj_parsed_time *pt);

/**
 * Encode date/time to time value.
 *
 * @param pt	The date/time.
 * @param tv	Variable to store time value result.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_time_encode(const pj_parsed_time *pt, pj_time_val *tv);

/**
 * Convert local time to GMT.
 *
 * @param tv	Time to convert.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_time_local_to_gmt(pj_time_val *tv);

/**
 * Convert GMT to local time.
 *
 * @param tv	Time to convert.
 *
 * @return zero if successfull.
 */
PJ_DECL(pj_status_t) pj_time_gmt_to_local(pj_time_val *tv);

/**
 * @}
 */

/* **************************************************************************/
#if defined(PJ_TERM_HAS_COLOR) && PJ_TERM_HAS_COLOR != 0

/**
 * @defgroup PJ_TERM Terminal
 * @ingroup PJ_OS
 * @{
 */

/**
 * Set current terminal color.
 *
 * @param color	    The RGB color.
 *
 * @return zero on success.
 */
PJ_DECL(pj_status_t) pj_term_set_color(pj_color_t color);

/**
 * Get current terminal foreground color.
 *
 * @return RGB color.
 */
PJ_DECL(pj_color_t) pj_term_get_color(void);

/**
 * @}
 */

#endif	/* PJ_TERM_HAS_COLOR */

/* **************************************************************************/
/**
 * @defgroup PJ_TIMESTAMP High Resolution Timestamp
 * @ingroup PJ_OS
 * @{
 *
 * PJLIB provides <b>High Resolution Timestamp</b> API to access highest 
 * resolution timestamp value provided by the platform. The API is usefull
 * to measure precise elapsed time, and can be used in applications such
 * as profiling.
 *
 * The timestamp value is represented in cycles, and can be related to
 * normal time (in seconds or sub-seconds) using various functions provided.
 *
 * \section pj_timestamp_examples_sec Examples
 *
 * For examples, please see:
 *  - \ref page_pjlib_sleep_test
 *  - \ref page_pjlib_timestamp_test
 */

/*
 * High resolution timer.
 */
#if defined(PJ_HAS_HIGH_RES_TIMER) && PJ_HAS_HIGH_RES_TIMER != 0

/**
 * Acquire high resolution timer value. The time value are stored
 * in cycles.
 *
 * @param ts	    High resolution timer value.
 * @return	    PJ_SUCCESS or the appropriate error code.
 *
 * @see pj_get_timestamp_freq().
 */
PJ_DECL(pj_status_t) pj_get_timestamp(pj_timestamp *ts);

/**
 * Get high resolution timer frequency, in cycles per second.
 *
 * @param freq	    Timer frequency, in cycles per second.
 * @return	    PJ_SUCCESS or the appropriate error code.
 */
PJ_DECL(pj_status_t) pj_get_timestamp_freq(pj_timestamp *freq);

/**
 * Set timestamp from 32bit values.
 * @param t	    The timestamp to be set.
 * @param hi	    The high 32bit part.
 * @param lo	    The low 32bit part.
 */
PJ_INLINE(void) pj_set_timestamp32(pj_timestamp *t, pj_uint32_t hi,
				   pj_uint32_t lo)
{
    t->u32.hi = hi;
    t->u32.lo = lo;
}

/**
 * Add timestamp t2 to t1.
 * @param t1	    t1.
 * @param t2	    t2.
 */
PJ_INLINE(void) pj_add_timestamp(pj_timestamp *t1, const pj_timestamp *t2)
{
#if PJ_HAS_INT64
    t1->u64 += t2->u64;
#else
    pj_uint32_t old = t1->u32.lo;
    t1->u32.hi += t2->u32.hi;
    t1->u32.lo += t2->u32.lo;
    if (t1->u32.lo < old)
	++t1->u32.hi;
#endif
}

/**
 * Add timestamp t2 to t1.
 * @param t1	    t1.
 * @param t2	    t2.
 */
PJ_INLINE(void) pj_add_timestamp32(pj_timestamp *t1, pj_uint32_t t2)
{
#if PJ_HAS_INT64
    t1->u64 += t2;
#else
    pj_uint32_t old = t1->u32.lo;
    t1->u32.lo += t2;
    if (t1->u32.lo < old)
	++t1->u32.hi;
#endif
}

/**
 * Substract timestamp t2 from t1.
 * @param t1	    t1.
 * @param t2	    t2.
 */
PJ_INLINE(void) pj_sub_timestamp(pj_timestamp *t1, const pj_timestamp *t2)
{
#if PJ_HAS_INT64
    t1->u64 -= t2->u64;
#else
    t1->u32.hi -= t2->u32.hi;
    if (t1->u32.lo >= t2->u32.lo)
	t1->u32.lo -= t2->u32.lo;
    else {
	t1->u32.lo -= t2->u32.lo;
	--t1->u32.hi;
    }
#endif
}

/**
 * Substract timestamp t2 from t1.
 * @param t1	    t1.
 * @param t2	    t2.
 */
PJ_INLINE(void) pj_sub_timestamp32(pj_timestamp *t1, pj_uint32_t t2)
{
#if PJ_HAS_INT64
    t1->u64 -= t2;
#else
    if (t1->u32.lo >= t2)
	t1->u32.lo -= t2;
    else {
	t1->u32.lo -= t2;
	--t1->u32.hi;
    }
#endif
}

/**
 * Get the timestamp difference between t2 and t1 (that is t2 minus t1),
 * and return a 32bit signed integer difference.
 */
PJ_INLINE(pj_int32_t) pj_timestamp_diff32(const pj_timestamp *t1,
					  const pj_timestamp *t2)
{
    /* Be careful with the signess (I think!) */
#if PJ_HAS_INT64
    pj_int64_t diff = t2->u64 - t1->u64;
    return (pj_int32_t) diff;
#else
    pj_int32 diff = t2->u32.lo - t1->u32.lo;
    return diff;
#endif
}


/**
 * Calculate the elapsed time, and store it in pj_time_val.
 * This function calculates the elapsed time using highest precision
 * calculation that is available for current platform, considering
 * whether floating point or 64-bit precision arithmetic is available. 
 * For maximum portability, application should prefer to use this function
 * rather than calculating the elapsed time by itself.
 *
 * @param start     The starting timestamp.
 * @param stop      The end timestamp.
 *
 * @return	    Elapsed time as #pj_time_val.
 *
 * @see pj_elapsed_usec(), pj_elapsed_cycle(), pj_elapsed_nanosec()
 */
PJ_DECL(pj_time_val) pj_elapsed_time( const pj_timestamp *start,
                                      const pj_timestamp *stop );

/**
 * Calculate the elapsed time as 32-bit miliseconds.
 * This function calculates the elapsed time using highest precision
 * calculation that is available for current platform, considering
 * whether floating point or 64-bit precision arithmetic is available. 
 * For maximum portability, application should prefer to use this function
 * rather than calculating the elapsed time by itself.
 *
 * @param start     The starting timestamp.
 * @param stop      The end timestamp.
 *
 * @return	    Elapsed time in milisecond.
 *
 * @see pj_elapsed_time(), pj_elapsed_cycle(), pj_elapsed_nanosec()
 */
PJ_DECL(pj_uint32_t) pj_elapsed_msec( const pj_timestamp *start,
                                      const pj_timestamp *stop );

/**
 * Calculate the elapsed time in 32-bit microseconds.
 * This function calculates the elapsed time using highest precision
 * calculation that is available for current platform, considering
 * whether floating point or 64-bit precision arithmetic is available. 
 * For maximum portability, application should prefer to use this function
 * rather than calculating the elapsed time by itself.
 *
 * @param start     The starting timestamp.
 * @param stop      The end timestamp.
 *
 * @return	    Elapsed time in microsecond.
 *
 * @see pj_elapsed_time(), pj_elapsed_cycle(), pj_elapsed_nanosec()
 */
PJ_DECL(pj_uint32_t) pj_elapsed_usec( const pj_timestamp *start,
                                      const pj_timestamp *stop );

/**
 * Calculate the elapsed time in 32-bit nanoseconds.
 * This function calculates the elapsed time using highest precision
 * calculation that is available for current platform, considering
 * whether floating point or 64-bit precision arithmetic is available. 
 * For maximum portability, application should prefer to use this function
 * rather than calculating the elapsed time by itself.
 *
 * @param start     The starting timestamp.
 * @param stop      The end timestamp.
 *
 * @return	    Elapsed time in nanoseconds.
 *
 * @see pj_elapsed_time(), pj_elapsed_cycle(), pj_elapsed_usec()
 */
PJ_DECL(pj_uint32_t) pj_elapsed_nanosec( const pj_timestamp *start,
                                         const pj_timestamp *stop );

/**
 * Calculate the elapsed time in 32-bit cycles.
 * This function calculates the elapsed time using highest precision
 * calculation that is available for current platform, considering
 * whether floating point or 64-bit precision arithmetic is available. 
 * For maximum portability, application should prefer to use this function
 * rather than calculating the elapsed time by itself.
 *
 * @param start     The starting timestamp.
 * @param stop      The end timestamp.
 *
 * @return	    Elapsed time in cycles.
 *
 * @see pj_elapsed_usec(), pj_elapsed_time(), pj_elapsed_nanosec()
 */
PJ_DECL(pj_uint32_t) pj_elapsed_cycle( const pj_timestamp *start,
                                       const pj_timestamp *stop );


#endif	/* PJ_HAS_HIGH_RES_TIMER */

/** @} */


/* **************************************************************************/
/**
 * Internal PJLIB function to initialize the threading subsystem.
 * @return          PJ_SUCCESS or the appropriate error code.
 */
pj_status_t pj_thread_init(void);


PJ_END_DECL

#endif  /* __PJ_OS_H__ */