-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathOSThread.h
1288 lines (1144 loc) · 37.2 KB
/
OSThread.h
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
/***************************************************************************************************************:')
OSThread.h
Threads handling.
Fabrice Le Bars
Created : 2007
***************************************************************************************************************:)*/
// Prevent Visual Studio Intellisense from defining _WIN32 and _MSC_VER when we use
// Visual Studio to edit Linux or Borland C++ code.
#ifdef __linux__
# undef _WIN32
#endif // __linux__
#if defined(__GNUC__) || defined(__BORLANDC__)
# undef _MSC_VER
#endif // defined(__GNUC__) || defined(__BORLANDC__)
#ifndef OSTHREAD_H
#define OSTHREAD_H
#include "OSTime.h"
/*
Debug macros specific to OSThread.
*/
#ifdef _DEBUG_MESSAGES_OSUTILS
# define _DEBUG_MESSAGES_OSTHREAD
#endif // _DEBUG_MESSAGES_OSUTILS
#ifdef _DEBUG_WARNINGS_OSUTILS
# define _DEBUG_WARNINGS_OSTHREAD
#endif // _DEBUG_WARNINGS_OSUTILS
#ifdef _DEBUG_ERRORS_OSUTILS
# define _DEBUG_ERRORS_OSTHREAD
#endif // _DEBUG_ERRORS_OSUTILS
#ifdef _DEBUG_MESSAGES_OSTHREAD
# define PRINT_DEBUG_MESSAGE_OSTHREAD(params) PRINT_DEBUG_MESSAGE(params)
#else
# define PRINT_DEBUG_MESSAGE_OSTHREAD(params)
#endif // _DEBUG_MESSAGES_OSTHREAD
#ifdef _DEBUG_WARNINGS_OSTHREAD
# define PRINT_DEBUG_WARNING_OSTHREAD(params) PRINT_DEBUG_WARNING(params)
#else
# define PRINT_DEBUG_WARNING_OSTHREAD(params)
#endif // _DEBUG_WARNINGS_OSTHREAD
#ifdef _DEBUG_ERRORS_OSTHREAD
# define PRINT_DEBUG_ERROR_OSTHREAD(params) PRINT_DEBUG_ERROR(params)
#else
# define PRINT_DEBUG_ERROR_OSTHREAD(params)
#endif // _DEBUG_ERRORS_OSTHREAD
// Always use CreateThread() for WINCE...
#ifdef WINCE
#ifndef USE_CREATE_THREAD
#define USE_CREATE_THREAD
#endif // USE_CREATE_THREAD
#endif // !WINCE
#ifdef _WIN32
#ifndef USE_CREATE_THREAD
#include <process.h>
#endif // !USE_CREATE_THREAD
#else
#include <pthread.h>
//#include <sched.h>
//#include <sys/resource.h>
#endif // _WIN32
#define MAX_THREAD_TIMEOUT (LONG_MAX-2)
// Default stack size for a thread (in bytes).
#define DEFAULT_THREAD_STACK_SIZE 1048576
#ifdef _WIN32
typedef DWORD THREAD_IDENTIFIER;
#ifdef USE_CREATE_THREAD
#define THREAD_PROC_RETURN_VALUE DWORD WINAPI
typedef LPTHREAD_START_ROUTINE PTHREAD_PROC;
#else
//#if defined(__cplusplus) && defined(_M_CEE)
//#define THREAD_PROC_RETURN_VALUE unsigned __clrcall
//typedef unsigned (__clrcall *PTHREAD_PROC)(void*);
//#else
#define THREAD_PROC_RETURN_VALUE unsigned __stdcall
typedef unsigned (__stdcall *PTHREAD_PROC)(void*);
//#endif // defined(__cplusplus) && defined(_M_CEE)
#endif // USE_CREATE_THREAD
#else
typedef pthread_t THREAD_IDENTIFIER;
#define THREAD_PROC_RETURN_VALUE void*
typedef void* (*PTHREAD_PROC)(void*);
// These priorities are only valid for Linux (might be different on other UNIX-like OS)
// and only THREAD_PRIORITY_IDLE is valid for a scheduling policy SCHED_OTHER whereas
// only the values between 1 and 99 are valid for the realtime policies SCHED_RR and
// SCHED_FIFO.
#define THREAD_PRIORITY_TIME_CRITICAL 99
#define THREAD_PRIORITY_HIGHEST 70
#define THREAD_PRIORITY_ABOVE_NORMAL 60
#define THREAD_PRIORITY_NORMAL 50
#define THREAD_PRIORITY_BELOW_NORMAL 40
#define THREAD_PRIORITY_LOWEST 1
#define THREAD_PRIORITY_IDLE 0
//// Portable programs should use sched_get_priority_min and sched_get_priority_max to
//// find the range of priorities supported for a particular policy.
//extern int THREAD_PRIORITY_TIME_CRITICAL;
//extern int THREAD_PRIORITY_HIGHEST;
//extern int THREAD_PRIORITY_ABOVE_NORMAL;
//extern int THREAD_PRIORITY_NORMAL;
//extern int THREAD_PRIORITY_BELOW_NORMAL;
//extern int THREAD_PRIORITY_LOWEST;
//extern int THREAD_PRIORITY_IDLE;
#endif // _WIN32
/*
Create a thread with default attributes.
The thread should be joinable (i.e. WaitForThread() should be called to wait for
its end).
To make it detached, call DetachThread() after CreateDefaultThread().
KillThread() or CancelThread() can also be called (whatever the joinable or detached
state, instead of WaitForThread() or DetachThread()), but the use of these functions is
not recommended in most of the cases.
PTHREAD_PROC pThreadProc : (IN) Pointer to the application-defined
function to be executed by the thread. This function should have this prototype :
THREAD_PROC_RETURN_VALUE function(void* pParam);
void* pParam : (IN) Pointer to a variable to be passed to the thread.
THREAD_IDENTIFIER* pThreadId : (INOUT) Valid pointer that will receive the
thread identifier.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int CreateDefaultThread(PTHREAD_PROC pThreadProc, void* pParam, THREAD_IDENTIFIER* pThreadId)
{
#ifdef _WIN32
// CreateThread is not advised when used in combination with the C standard library...
// But it is not clear whether it is a problem in our case...
#ifdef USE_CREATE_THREAD
HANDLE hThread = CreateThread(
NULL, // Default security attributes.
DEFAULT_THREAD_STACK_SIZE, // Initial size of the stack, in bytes.
pThreadProc, // Thread function.
pParam, // Argument to thread function.
0, // Use default creation flags.
pThreadId); // Returns the thread identifier.
if (hThread == NULL)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
pThreadProc, pParam));
return EXIT_FAILURE;
}
#else
HANDLE hThread = (HANDLE)_beginthreadex(
NULL, // Default security attributes.
DEFAULT_THREAD_STACK_SIZE, // Initial size of the stack, in bytes.
pThreadProc, // Thread function.
pParam, // Argument to thread function.
0, // Use default creation flags.
(unsigned int*)pThreadId); // Returns the thread identifier.
if (hThread == NULL)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"_beginthreadex failed. ",
pThreadProc, pParam));
return EXIT_FAILURE;
}
#endif // USE_CREATE_THREAD
// Close the thread handle (this does not terminate the thread and makes the handle
// returned by CreateThread() be closed automatically and invalid when the thread terminates,
// if no other handles to it are opened. Anyway, all the resources used by the thread will
// be released when it is terminated and all the handles to it are closed).
if (!CloseHandle(hThread))
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
pThreadProc, pParam));
return EXIT_FAILURE;
}
#else
pthread_attr_t attr;
int policy = 0;
struct sched_param param;
//int prio_max = 0;
//int prio_min = 0;
// Initialize thread attribute.
if (pthread_attr_init(&attr) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"pthread_attr_init failed. ",
pThreadProc, pParam));
return EXIT_FAILURE;
}
// Set a default stacksize.
if (pthread_attr_setstacksize(&attr, DEFAULT_THREAD_STACK_SIZE) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"pthread_attr_setstacksize failed. ",
pThreadProc, pParam));
pthread_attr_destroy(&attr);
return EXIT_FAILURE;
}
// Set the thread as joinable. This is the default on Linux.
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
#ifndef __ANDROID__
// Indicate whether the scheduling policy and scheduling parameters for the
// newly created thread are determined by the values of the schedpolicy and
// schedparam attributes (value PTHREAD_EXPLICIT_SCHED) or are inherited from
// the parent thread (value PTHREAD_INHERIT_SCHED).
if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"pthread_attr_setinheritsched failed. ",
pThreadProc, pParam));
pthread_attr_destroy(&attr);
return EXIT_FAILURE;
}
#endif // !__ANDROID__
// Only PTHREAD_SCOPE_SYSTEM is supported on Linux. This is the default on Linux.
// That is a pity as PTHREAD_SCOPE_PROCESS seems to describe a behaviour similar
// to Windows threads and process for priorities but it is not clear...
//if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS) != EXIT_SUCCESS)
//{
// PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
// "(pThreadProc=%#x, pParam=%#x)\n",
// strtime_m(),
// "pthread_attr_setscope failed. ",
// pThreadProc, pParam));
// pthread_attr_destroy(&attr);
// return EXIT_FAILURE;
//}
// Set the scheduling policy attribute of the thread. The supported values
// are SCHED_FIFO, SCHED_RR, and SCHED_OTHER.
policy = SCHED_OTHER;
if (pthread_attr_setschedpolicy(&attr, policy) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"pthread_attr_setschedpolicy failed. ",
pThreadProc, pParam));
pthread_attr_destroy(&attr);
return EXIT_FAILURE;
}
// Set the priority of the thread.
// For the SCHED_OTHER policy, sched_priority is not used in scheduling decisions
// (it must be specified as 0).
param.sched_priority = 0;
if (pthread_attr_setschedparam(&attr, ¶m) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"pthread_attr_setschedparam failed. ",
pThreadProc, pParam));
pthread_attr_destroy(&attr);
return EXIT_FAILURE;
}
//// To retrieve the priorities in case of realtime scheduling policies.
//pthread_attr_getschedpolicy(&attr, &policy);
//prio_max = sched_get_priority_max(policy);
//prio_min = sched_get_priority_min(policy);
//PRINT_DEBUG_MESSAGE_OSTHREAD(("prio_min = %d\n", prio_min));
//PRINT_DEBUG_MESSAGE_OSTHREAD(("prio_max = %d\n", prio_max));
//// Maybe find better quantified values...
//THREAD_PRIORITY_TIME_CRITICAL = prio_max;
//THREAD_PRIORITY_HIGHEST = (prio_max-(prio_max+prio_min+1)/2)*2/3+(prio_max+prio_min+1)/2;
//THREAD_PRIORITY_ABOVE_NORMAL = (prio_max-(prio_max+prio_min+1)/2)/3+(prio_max+prio_min+1)/2;
//THREAD_PRIORITY_NORMAL = (prio_max+prio_min+1)/2;
//THREAD_PRIORITY_BELOW_NORMAL = ((prio_max+prio_min+1)/2-prio_min)/2+prio_min;
//THREAD_PRIORITY_LOWEST = prio_min;
//THREAD_PRIORITY_IDLE = 0;
//// 31 corresponds to THREAD_PRIORITY_TIME_CRITICAL-THREAD_PRIORITY_IDLE+1
//// (number of levels of priority) for Windows.
//// Unix should have at least 32 distinct priority levels.
if (pthread_create(pThreadId, &attr, pThreadProc, pParam) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"pthread_create failed. ",
pThreadProc, pParam));
pthread_attr_destroy(&attr);
return EXIT_FAILURE;
}
// Free attribute.
if (pthread_attr_destroy(&attr) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CreateDefaultThread error (%s) : %s"
"(pThreadProc=%#x, pParam=%#x)\n",
strtime_m(),
"pthread_attr_destroy failed. ",
pThreadProc, pParam));
pthread_detach(*pThreadId);
#ifndef __ANDROID__
pthread_cancel(*pThreadId);
#endif // !__ANDROID__
return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
/*
Put a thread created by CreateDefaultThread() in a detached state.
A call to WaitForThread() will be useless and should fail.
All the memory used by the thread object should be released when it terminates.
THREAD_IDENTIFIER ThreadId : (IN) The thread identifier.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int DetachThread(THREAD_IDENTIFIER ThreadId)
{
#ifdef _WIN32
// For Windows, there is no problem of detached or joinable state.
// Anyway, all the resources used by the thread are released when
// it is terminated and all the handles to it are closed.
// All attempts to open a handle to it after it is terminated will fail.
// And while it is not terminated, we can wait for it with WaitForSingleObject().
UNREFERENCED_PARAMETER(ThreadId);
#else
// Indicate that storage for the thread can be reclaimed when it terminates.
// Note : pthread_detach() may fail if the thread identifier is bad. This can be because
// it was an invalid thread identifier or the thread has already terminated but this would mean that
// pthread_detach() or pthread_join() have already been called successfully...
if (pthread_detach(ThreadId) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("DetachThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
"pthread_detach failed. ",
ThreadId));
return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
/*
Wait until the thread identified by ThreadId has terminated.
THREAD_IDENTIFIER ThreadId : (IN) The thread identifier.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int WaitForThread(THREAD_IDENTIFIER ThreadId)
{
#ifdef _WIN32
// For Windows, there is no problem of detached or joinable state.
// Anyway, all the resources used by the thread are released when
// it is terminated and all the handles to it are closed.
// All attempts to open a handle to it after it is terminated will fail.
// And while it is not terminated, we can wait for it with WaitForSingleObject().
#ifndef WINCE
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, ThreadId);
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
if (hThread == NULL)
{
PRINT_DEBUG_WARNING_OSTHREAD(("WaitForThread warning (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
}
else
{
// The thread is not already terminated.
// Wait until the thread has terminated.
if (WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED)
{
PRINT_DEBUG_ERROR_OSTHREAD(("WaitForThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
CloseHandle(hThread);
return EXIT_FAILURE;
}
// Close the thread handle.
if (!CloseHandle(hThread))
{
PRINT_DEBUG_ERROR_OSTHREAD(("WaitForThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
return EXIT_FAILURE;
}
}
#else
// For WINCE, the thread identifier is the handle of the thread.
HANDLE hThread = (HANDLE)ThreadId;
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
if (WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED)
{
PRINT_DEBUG_WARNING_OSTHREAD(("WaitForThread warning (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
}
#endif // !WINCE
#else
// Wait until the thread has terminated.
// Note : pthread_join() may fail if the thread identifier is bad. This can be because
// it was an invalid thread identifier or the thread has already terminated but this would mean that
// pthread_detach() or pthread_join() have already been called successfully...
if (pthread_join(ThreadId, NULL) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("WaitForThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
"pthread_join failed. ",
ThreadId));
return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
// Disabled by default because not always available under Linux.
#ifdef ENABLE_WAIT_FOR_THREAD_TIMEOUT
/*
Wait until the thread identified by ThreadId has terminated or a timeout
elapse.
THREAD_IDENTIFIER ThreadId : (IN) The thread identifier.
int timeout : (IN) Timeout in ms (max is MAX_THREAD_TIMEOUT).
Return : EXIT_SUCCESS if the thread was successfully joined, EXIT_TIMEOUT if
the timeout elapse or EXIT_FAILURE if there is an error.
*/
inline int WaitForThreadWithTimeout(THREAD_IDENTIFIER ThreadId, int timeout)
{
#ifdef _WIN32
DWORD dwWaitResult = WAIT_FAILED;
// For Windows, there is no problem of detached or joinable state.
// Anyway, all the resources used by the thread are released when
// it is terminated and all the handles to it are closed.
// All attempts to open a handle to it after it is terminated will fail.
// And while it is not terminated, we can wait for it with WaitForSingleObject().
#ifndef WINCE
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, ThreadId);
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
if (hThread == NULL)
{
PRINT_DEBUG_WARNING_OSTHREAD(("WaitForThreadWithTimeout warning (%s) : %s"
"(ThreadId=%#x, timeout=%d)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId, timeout));
}
else
{
// The thread is not already terminated.
// Wait until the thread has terminated.
dwWaitResult = WaitForSingleObject(hThread, (DWORD)timeout);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
// The thread was successfully joined.
break;
case WAIT_TIMEOUT:
CloseHandle(hThread);
return EXIT_TIMEOUT;
default:
PRINT_DEBUG_ERROR_OSTHREAD(("WaitForThreadWithTimeout error (%s) : %s"
"(ThreadId=%#x, timeout=%d)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId, timeout));
CloseHandle(hThread);
return EXIT_FAILURE;
}
// Close the thread handle.
if (!CloseHandle(hThread))
{
PRINT_DEBUG_ERROR_OSTHREAD(("WaitForThreadWithTimeout error (%s) : %s"
"(ThreadId=%#x, timeout=%d)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId, timeout));
return EXIT_FAILURE;
}
}
#else
// For WINCE, the thread identifier is the handle of the thread.
HANDLE hThread = (HANDLE)ThreadId;
dwWaitResult = WaitForSingleObject(hThread, (DWORD)timeout);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
// The thread was successfully joined.
break;
case WAIT_TIMEOUT:
return EXIT_TIMEOUT;
default:
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
PRINT_DEBUG_WARNING_OSTHREAD(("WaitForThreadWithTimeout warning (%s) : %s"
"(ThreadId=%#x, timeout=%d)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId, timeout));
break;
}
#endif // !WINCE
#else
int iResult = EXIT_FAILURE;
struct timespec abstime;
// Calculate relative interval as current time plus duration given by timeout.
if (clock_gettime(CLOCK_REALTIME, &abstime) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("WaitForThreadWithTimeout error (%s) : %s"
"(ThreadId=%#x, timeout=%d)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId, timeout));
return EXIT_FAILURE;
}
abstime.tv_sec += timeout/1000; // Seconds.
abstime.tv_nsec += (timeout%1000)*1000000; // Additional nanoseconds.
abstime.tv_sec += abstime.tv_nsec/1000000000;
abstime.tv_nsec = abstime.tv_nsec%1000000000;
// Wait until the thread has terminated.
// Note : pthread_timedjoin_np() may fail if the thread identifier is bad. This can be because
// it was an invalid thread identifier or the thread has already terminated but this would mean that
// pthread_detach() or pthread_join() have already been called successfully...
iResult = pthread_timedjoin_np(ThreadId, NULL, &abstime);
switch (iResult)
{
case EXIT_SUCCESS:
break;
case ETIMEDOUT:
return EXIT_TIMEOUT;
default:
PRINT_DEBUG_ERROR_OSTHREAD(("WaitForThreadWithTimeout error (%s) : %s"
"(ThreadId=%#x, timeout=%d)\n",
strtime_m(),
"pthread_timedjoin_np failed. ",
ThreadId, timeout));
return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
#endif // ENABLE_WAIT_FOR_THREAD_TIMEOUT
// Bad to use, but if it can avoid using the task manager to kill an application...
#ifdef ENABLE_KILL_THREAD
#ifdef _MSC_VER
// Disable Visual Studio warnings about TerminateThread().
#pragma warning(disable : 6258)
#endif // _MSC_VER
/*
Enable the use of either KillThread() or CancelThread() for the current thread.
Note that by default (if KillOrCancelThreadMode() was never called for the current
thread), it is CancelThread() that is enabled.
BOOL bKill : (IN) FALSE to enable CancelThread() otherwise KillThread() is enabled.
Return : Nothing.
*/
inline void KillOrCancelThreadMode(BOOL bKill)
{
#ifdef _WIN32
// For Windows, KillThread() or CancelThread() can be used without restrictions
// (except that they are dangerous and uncommon functions that must be used with care).
UNREFERENCED_PARAMETER(bKill);
#else
if (bKill)
{
// When initially created, a thread is synchronously cancelable.
// Here enable the current thread to be canceled (killed) asynchronously (i.e. immediately).
//pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
}
else
{
// When initially created, a thread is synchronously cancelable.
// Here reset to this default cancel state.
//pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
}
#endif // _WIN32
}
/*
Terminate a thread immediately.
The thread to terminate should have called KillOrCancelThreadMode(TRUE) before, otherwise the results are
undefined.
It is a dangerous function that should only be used in the most extreme cases
You should call KillThread() only if you know exactly what the target thread is doing, and you control
all of the code that the target thread could possibly be running at the time of the termination (C++
destructors might not be called automatically...).
THREAD_IDENTIFIER ThreadId : (IN) The thread identifier.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int KillThread(THREAD_IDENTIFIER ThreadId)
{
#ifdef _WIN32
#ifndef WINCE
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, ThreadId);
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
if (hThread == NULL)
{
PRINT_DEBUG_WARNING_OSTHREAD(("KillThread warning (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
}
else
{
if (!TerminateThread(hThread, EXIT_KILLED_THREAD))
{
PRINT_DEBUG_ERROR_OSTHREAD(("KillThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
CloseHandle(hThread);
return EXIT_FAILURE;
}
if (!CloseHandle(hThread))
{
PRINT_DEBUG_ERROR_OSTHREAD(("KillThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
return EXIT_FAILURE;
}
}
#else
// For WINCE, the thread identifier is the handle of the thread.
HANDLE hThread = (HANDLE)ThreadId;
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
if (!TerminateThread(hThread, EXIT_KILLED_THREAD))
{
PRINT_DEBUG_WARNING_OSTHREAD(("KillThread warning (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
}
#endif // !WINCE
#else
int iResult = pthread_detach(ThreadId);
switch (iResult)
{
case EXIT_SUCCESS:
break;
case EINVAL:
// The thread is already detached.
break;
default:
PRINT_DEBUG_ERROR_OSTHREAD(("KillThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
"pthread_detach failed. ",
ThreadId));
return EXIT_FAILURE;
}
// By default, a thread is synchronously cancelable. But if KillOrCancelThread(TRUE) is
// called from its thread function, it should have been set to asynchronously cancelable
// (i.e. can be killed immediately).
if (pthread_cancel(ThreadId) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("KillThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
"pthread_cancel failed. ",
ThreadId));
return EXIT_FAILURE;
}
// Instead of detaching, it could be also possible to join...
//int iResult = pthread_join(ThreadId, NULL);
//switch (iResult)
//{
//case EXIT_SUCCESS:
// break;
//case EINVAL:
// // The thread is detached.
// break;
//default:
// PRINT_DEBUG_ERROR_OSTHREAD(("KillThread error (%s) : %s"
// "(ThreadId=%#x)\n",
// strtime_m(),
// "pthread_join failed. ",
// ThreadId));
// return EXIT_FAILURE;
//}
#endif // _WIN32
return EXIT_SUCCESS;
}
#ifdef _MSC_VER
// Restore the Visual Studio warnings previously disabled.
#pragma warning(default : 6258)
#endif // _MSC_VER
#endif // ENABLE_KILL_THREAD
// Bad to use, but if it can avoid using the task manager to kill an application...
#ifdef ENABLE_CANCEL_THREAD
#ifdef _WIN32
EXTERN_C VOID CALLBACK _CancelThreadAPC(ULONG_PTR dwParam);
#endif // _WIN32
/*
Cancel a thread.
If the thread to cancel have called KillOrCancelThreadMode(TRUE) before, the results are
undefined unless KillOrCancelThreadMode(FALSE) was called to reset to the default
behaviour (CancelThread() enabled and KillThread() disabled).
The thread should only exit when it calls a function that is a
cancellation point (use TestCancelThread() to create a cancellation point but note also
that other functions may have internal cancellation points).
It is a dangerous function that should only be used in the most extreme cases
You should call CancelThread() only if you know exactly what the target thread is doing, and you control
all of the code that the target thread could possibly be running at the time of the termination (C++
destructors might not be called automatically...).
THREAD_IDENTIFIER ThreadId : (IN) The thread identifier.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int CancelThread(THREAD_IDENTIFIER ThreadId)
{
#ifdef _WIN32
#ifndef WINCE
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, ThreadId);
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
if (hThread == NULL)
{
PRINT_DEBUG_WARNING_OSTHREAD(("CancelThread warning (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
}
else
{
// if (!QueueUserAPC(_CancelThreadAPC, hThread, (ULONG_PTR)hThread))
if (!QueueUserAPC(_CancelThreadAPC, hThread, 0))
{
PRINT_DEBUG_ERROR_OSTHREAD(("CancelThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
CloseHandle(hThread);
return EXIT_FAILURE;
}
if (!CloseHandle(hThread))
{
PRINT_DEBUG_ERROR_OSTHREAD(("CancelThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
return EXIT_FAILURE;
}
// CloseHandle() called from _CancelThreadAPC()?
}
#else
// For WINCE, the thread identifier is the handle of the thread.
HANDLE hThread = (HANDLE)ThreadId;
// Should check GetLastError() to see if there is a permission problem...
// Here we do not know if it failed because the thread has already terminated
// or there was another problem...
// if (!QueueUserAPC(_CancelThreadAPC, hThread, (ULONG_PTR)hThread))
if (!QueueUserAPC(_CancelThreadAPC, hThread, 0))
{
PRINT_DEBUG_WARNING_OSTHREAD(("CancelThread warning (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
GetLastErrorMsg(),
ThreadId));
}
#endif // !WINCE
#else
int iResult = pthread_detach(ThreadId);
switch (iResult)
{
case EXIT_SUCCESS:
break;
case EINVAL:
// The thread is already detached.
break;
default:
PRINT_DEBUG_ERROR_OSTHREAD(("CancelThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
"pthread_detach failed. ",
ThreadId));
return EXIT_FAILURE;
}
// When initially created, a thread is synchronously cancelable.
// The thread should only exit when it calls a function that is a
// cancellation point (such as read(), write(), sleep(), wait(), pthread_testcancel()...).
if (pthread_cancel(ThreadId) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSTHREAD(("CancelThread error (%s) : %s"
"(ThreadId=%#x)\n",
strtime_m(),
"pthread_cancel failed. ",
ThreadId));
return EXIT_FAILURE;
}
// Instead of detaching, it could be also possible to join...
//int iResult = pthread_join(ThreadId, NULL);
//switch (iResult)
//{
//case EXIT_SUCCESS:
// break;
//case EINVAL:
// // The thread is detached.
// break;
//default:
// PRINT_DEBUG_ERROR_OSTHREAD(("CancelThread error (%s) : %s"
// "(ThreadId=%#x)\n",
// strtime_m(),
// "pthread_join failed. ",
// ThreadId));
// return EXIT_FAILURE;
//}
#endif // _WIN32
return EXIT_SUCCESS;
}
/*
Create a cancellation point in the current thread.
Return : Nothing.
*/
inline void TestCancelThread(void)
{
#ifdef _WIN32
SleepEx(0, TRUE);
#else
pthread_testcancel();
#endif // _WIN32
}
#endif // ENABLE_CANCEL_THREAD
/*
Compare 2 thread identifiers.
THREAD_IDENTIFIER ThreadId1 : (IN) First thread identifier.
THREAD_IDENTIFIER ThreadId2 : (IN) Second thread identifier.
Return : TRUE or FALSE.
*/
inline BOOL CompareThreadId(THREAD_IDENTIFIER ThreadId1, THREAD_IDENTIFIER ThreadId2)
{
#ifdef _WIN32
if (ThreadId1 == ThreadId2)
{
return TRUE;
}
else
{
return FALSE;
}
#else
if (pthread_equal(ThreadId1, ThreadId2))
{
return TRUE;
}
else
{
return FALSE;
}
#endif // _WIN32
}
#ifdef _WIN32
#else
/*
Retrieve the thread identifier of the calling thread.
Return : The thread identifier.
*/
inline THREAD_IDENTIFIER GetCurrentThreadId(void)
{
return pthread_self();
}
#endif // _WIN32
/*
Cause the calling thread to yield execution to another thread that is ready to
run.
Return : Nothing.
*/
inline void ThreadYield(void)
{
#ifdef _WIN32
#ifndef WINCE
SwitchToThread();
#else
Sleep(0);
#endif // !WINCE
#else