summaryrefslogtreecommitdiff
path: root/ace/Thread_Manager.cpp
blob: 569fdb59ffc26af06dde3c57863b90e4dc65bcb4 (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
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
// $Id$

#include "ace/Synch_T.h"
#include "ace/Thread_Manager.h"
#include "ace/Dynamic.h"
#include "ace/Object_Manager.h"
#include "ace/Singleton.h"
#include "ace/Auto_Ptr.h"
#include "ace/Thread_Exit.h"

#if !defined (__ACE_INLINE__)
#include "ace/Thread_Manager.i"
#endif /* __ACE_INLINE__ */

ACE_RCSID(ace, Thread_Manager, "$Id$")

ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Control)
ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Manager)

#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS)
// Process-wide Thread Manager.
ACE_Thread_Manager *ACE_Thread_Manager::thr_mgr_ = 0;

// Controls whether the Thread_Manager is deleted when we shut down
// (we can only delete it safely if we created it!)
int ACE_Thread_Manager::delete_thr_mgr_ = 0;
#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */

void
ACE_Thread_Manager::dump (void)
{
  ACE_TRACE ("ACE_Thread_Manager::dump");
  // Cast away const-ness of this in order to use its non-const lock_.
  ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon,
                     ((ACE_Thread_Manager *) this)->lock_));

  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));

  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\ngrp_id_ = %d"), this->grp_id_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\ncurrent_count_ = %d"), this->thr_list_.size ()));

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    iter.next ()->dump ();

  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
}

ACE_Thread_Descriptor::~ACE_Thread_Descriptor (void)
{
  delete this->sync_;
}

#if !defined(ACE_USE_ONE_SHOT_AT_THREAD_EXIT)
void ACE_Thread_Descriptor::at_pop (int apply)

{
  ACE_TRACE ("ACE_Thread_Descriptor::at_pop");
  // Get first at from at_exit_list
  ACE_At_Thread_Exit* at = this->at_exit_list_;
  // Remove at from at_exit list
  this->at_exit_list_ = at->next_;
  // Apply if required
  if (apply)
   {
     at->apply ();
     // Do the apply method
     at->was_applied (1);
     // Mark at has been applied to avoid double apply from
     // at destructor
   }
  // If at is not owner delete at.
  if (!at->is_owner ())
   delete at;
}

void
ACE_Thread_Descriptor::at_push (ACE_At_Thread_Exit* cleanup, int is_owner)

{
  ACE_TRACE ("ACE_Thread_Descriptor::at_push");
  cleanup->is_owner (is_owner);
  cleanup->td_ = this;
  cleanup->next_ = at_exit_list_;
  at_exit_list_ = cleanup;
}

int
ACE_Thread_Descriptor::at_exit (ACE_At_Thread_Exit& cleanup)

{
  ACE_TRACE ("ACE_Thread_Descriptor::at_exit");
  at_push (&cleanup, 1);
  return 0;
}

int
ACE_Thread_Descriptor::at_exit (ACE_At_Thread_Exit* cleanup)

{
  ACE_TRACE ("ACE_Thread_Descriptor::at_exit");
  if (cleanup==0)
   return -1;
  else
   {
     this->at_push (cleanup);
     return 0;
   }
}

void
ACE_Thread_Descriptor::do_at_exit ()

{
  ACE_TRACE ("ACE_Thread_Descriptor::do_at_exit");
  while (at_exit_list_!=0)
    this->at_pop ();
}

void
ACE_Thread_Descriptor::terminate ()

{
  ACE_TRACE ("ACE_Thread_Descriptor::terminate");

  if (!terminated_)
   {
     ACE_Log_Msg* log_msg = this->log_msg_;
     terminated_ = 1;
     // Run at_exit hooks
     this->do_at_exit ();
     // We must remove Thread_Descriptor from Thread_Manager list
     if (this->tm_ != 0)
      {
         int close_handle = 0;

#if !defined (VXWORKS)
         // Threads created with THR_DAEMON shouldn't exist here, but
         // just to be safe, let's put it here.

         if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_JOINING))
           {
             if (ACE_BIT_DISABLED (this->flags_, THR_DETACHED | THR_DAEMON)
                 || ACE_BIT_ENABLED (this->flags_, THR_JOINABLE))
               {
                 // Mark thread as terminated.
                 ACE_SET_BITS (this->thr_state_, ACE_Thread_Manager::ACE_THR_TERMINATED);
                 tm_->register_as_terminated (this);
                 // Must copy the information here because td will be
                 // "freed" below.
               }
#if defined (ACE_WIN32)
             else
               {
                 close_handle = 1;
               }
#endif /* ACE_WIN32 */
           }
#endif /* ! VXWORKS */

         // Remove thread descriptor from the table.
         if (this->tm_ != 0)
           tm_->remove_thr (this, close_handle);
      }

     // Check if we need delete ACE_Log_Msg instance
     // If ACE_TSS_cleanup was not executed first log_msg == 0
     if (log_msg == 0)
      {
        // Only inform to ACE_TSS_cleanup that it must delete the log instance
        // setting ACE_LOG_MSG thr_desc to 0.
        ACE_LOG_MSG->thr_desc (0);
      }
     else
      {
        // Thread_Descriptor is the owner of the Log_Msg instance!!
        // deleted.
        this->log_msg_ = 0;
        delete log_msg;
      }
   }
}

#endif /* !ACE_USE_ONE_SHOT_AT_THREAD_EXIT */

int
ACE_Thread_Descriptor::at_exit (void *object,
                                ACE_CLEANUP_FUNC cleanup_hook,
                                void *param)
{
  ACE_TRACE ("ACE_Thread_Descriptor::at_exit");
#if defined(ACE_USE_ONE_SHOT_AT_THREAD_EXIT)
  this->cleanup_info_.cleanup_hook_ = cleanup_hook;
  this->cleanup_info_.object_ = object;
  this->cleanup_info_.param_ = param;
#else
  // To keep compatibility, when cleanup_hook is null really is a at_pop
  // without apply.
  if (cleanup_hook == 0)
   {
     if (this->at_exit_list_!= 0)
      this->at_pop(0);
   }
  else
   {
     ACE_At_Thread_Exit* cleanup;
     ACE_NEW_RETURN (cleanup,
                     ACE_At_Thread_Exit_Func (object,
                                              cleanup_hook,
                                              param),
                     -1);
     this->at_push (cleanup);
   }
#endif /* ACE_USE_ONE_SHOT_AT_THREAD_EXIT */
  return 0;
}

void
ACE_Thread_Descriptor::dump (void) const
{
  ACE_TRACE ("ACE_Thread_Descriptor::dump");
  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));

  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nthr_id_ = %d"), this->thr_id_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nthr_handle_ = %d"), this->thr_handle_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\ngrp_id_ = %d"), this->grp_id_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nthr_state_ = %d"), this->thr_state_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\ncleanup_info_.cleanup_hook_ = %x"), this->cleanup_info_.cleanup_hook_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nflags_ = %x\n"), this->flags_));

  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
}

ACE_Thread_Descriptor::ACE_Thread_Descriptor (void)
  :
#if !defined(ACE_USE_ONE_SHOT_AT_THREAD_EXIT)
    log_msg_ (0),
    at_exit_list_ (0),
    terminated_ (0)
#endif /* !ACE_USE_ONE_SHOT_AT_THREAD_EXIT */
{
  ACE_TRACE ("ACE_Thread_Descriptor::ACE_Thread_Descriptor");
  ACE_NEW (this->sync_,
           ACE_DEFAULT_THREAD_MANAGER_LOCK);
}

void
ACE_Thread_Descriptor::acquire_release (void)
{
  // Just try to acquire the lock then release it.
#if defined (ACE_THREAD_MANAGER_USES_SAFE_SPAWN)
  if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED))
#endif /* ACE_THREAD_MANAGER_USES_SAFE_SPAWN */
    {
      this->sync_->acquire ();
      // Acquire the lock before removing <td> from the thread table.  If
      // this thread is in the table already, it should simply acquire the
      // lock easily.

      // Once we get the lock, we must have registered.
      ACE_ASSERT (ACE_BIT_ENABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED));

      this->sync_->release ();
      // Release the lock before putting it back to freelist.
    }
}

// The following macro simplifies subsequence code.
#define ACE_FIND(OP,INDEX) \
  ACE_Thread_Descriptor *INDEX = OP; \

ACE_Thread_Descriptor *
ACE_Thread_Manager::thread_descriptor (ACE_thread_t thr_id)
{
  ACE_TRACE ("ACE_Thread_Manager::thread_descriptor");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));

  ACE_FIND (this->find_thread (thr_id), ptr);
  return ptr;
}

ACE_Thread_Descriptor *
ACE_Thread_Manager::hthread_descriptor (ACE_hthread_t thr_handle)
{
  ACE_TRACE ("ACE_Thread_Manager::hthread_descriptor");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));

  ACE_FIND (this->find_hthread (thr_handle), ptr);
  return ptr;
}

// Return the thread descriptor (indexed by ACE_hthread_t).

int
ACE_Thread_Manager::thr_self (ACE_hthread_t &self)
{
  ACE_TRACE ("ACE_Thread_Manager::thr_self");

  ACE_Thread_Descriptor *desc =
    this->thread_desc_self ();

  if (desc == 0)
    return -1;
  else
    desc->self (self);

  return 0;
}

// Initialize the synchronization variables.

ACE_Thread_Manager::ACE_Thread_Manager (size_t prealloc,
                                        size_t lwm,
                                        size_t inc,
                                        size_t hwm)
  : grp_id_ (1),
    automatic_wait_ (1)
#if defined (ACE_HAS_THREADS)
    , zero_cond_ (lock_)
#endif /* ACE_HAS_THREADS */
    , thread_desc_freelist_ (ACE_FREE_LIST_WITH_POOL,
                             prealloc, lwm, hwm, inc)
{
  ACE_TRACE ("ACE_Thread_Manager::ACE_Thread_Manager");
}

#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS)
ACE_Thread_Manager *
ACE_Thread_Manager::instance (void)
{
  ACE_TRACE ("ACE_Thread_Manager::instance");

  if (ACE_Thread_Manager::thr_mgr_ == 0)
    {
      // Perform Double-Checked Locking Optimization.
      ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon,
                                *ACE_Static_Object_Lock::instance (), 0));

      if (ACE_Thread_Manager::thr_mgr_ == 0)
        {
          ACE_NEW_RETURN (ACE_Thread_Manager::thr_mgr_,
                          ACE_Thread_Manager,
                          0);
          ACE_Thread_Manager::delete_thr_mgr_ = 1;
        }
    }

  return ACE_Thread_Manager::thr_mgr_;
}

ACE_Thread_Manager *
ACE_Thread_Manager::instance (ACE_Thread_Manager *tm)
{
  ACE_TRACE ("ACE_Thread_Manager::instance");
  ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon,
                            *ACE_Static_Object_Lock::instance (), 0));

  ACE_Thread_Manager *t = ACE_Thread_Manager::thr_mgr_;
  // We can't safely delete it since we don't know who created it!
  ACE_Thread_Manager::delete_thr_mgr_ = 0;

  ACE_Thread_Manager::thr_mgr_ = tm;
  return t;
}

void
ACE_Thread_Manager::close_singleton (void)
{
  ACE_TRACE ("ACE_Thread_Manager::close_singleton");

  ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon,
                     *ACE_Static_Object_Lock::instance ()));

  if (ACE_Thread_Manager::delete_thr_mgr_)
    {
      // First, we clean up the thread descriptor list.
      ACE_Thread_Manager::thr_mgr_->close ();
      delete ACE_Thread_Manager::thr_mgr_;
      ACE_Thread_Manager::thr_mgr_ = 0;
      ACE_Thread_Manager::delete_thr_mgr_ = 0;
    }
}
#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */

// Close up and release all resources.

int
ACE_Thread_Manager::close ()
{
  ACE_TRACE ("ACE_Thread_Manager::close");

  // Clean up the thread descriptor list.
  if (this->automatic_wait_)
    this->wait (0, 1);
  else
    {
      ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

      this->remove_thr_all ();
    }

  return 0;
}

ACE_Thread_Manager::~ACE_Thread_Manager (void)
{
  ACE_TRACE ("ACE_Thread_Manager::~ACE_Thread_Manager");
  this->close ();
}


// Run the entry point for thread spawned under the control of the
// <ACE_Thread_Manager>.  This must be an extern "C" to make certain
// compilers happy...
//
// The interaction with <ACE_Thread_Exit> and
// <ace_thread_manager_adapter> works like this, with
// ACE_HAS_THREAD_SPECIFIC_STORAGE or ACE_HAS_TSS_EMULATION:
//
// o Every thread in the <ACE_Thread_Manager> is run with
//   <ace_thread_manager_adapter>.
//
// o <ace_thread_manager_adapter> retrieves the singleton
//   <ACE_Thread_Exit> instance from <ACE_Thread_Exit::instance>.
//   The singleton gets created in thread-specific storage
//   in the first call to that function.  The key point is that the
//   instance is in thread-specific storage.
//
// o A thread can exit by various means, such as <ACE_Thread::exit>, C++
//   or Win32 exception, "falling off the end" of the thread entry
//   point function, etc.
//
// o If you follow this so far, now it gets really fun . . .
//   When the thread-specific storage (for the thread that
//   is being destroyed) is cleaned up, the OS threads package (or
//   the ACE emulation of thread-specific storage) will destroy any
//   objects that are in thread-specific storage.  It has a list of
//   them, and just walks down the list and destroys each one.
//
// o That's where the ACE_Thread_Exit destructor gets called.

#if defined(ACE_USE_THREAD_MANAGER_ADAPTER)
extern "C" void *
ace_thread_manager_adapter (void *args)
{
#if defined (ACE_HAS_TSS_EMULATION)
  // As early as we can in the execution of the new thread, allocate
  // its local TS storage.  Allocate it on the stack, to save dynamic
  // allocation/dealloction.
  void *ts_storage[ACE_TSS_Emulation::ACE_TSS_THREAD_KEYS_MAX];
  ACE_TSS_Emulation::tss_open (ts_storage);
#endif /* ACE_HAS_TSS_EMULATION */

  ACE_Thread_Adapter *thread_args = (ACE_Thread_Adapter *) args;

  // NOTE: this preprocessor directive should match the one in above
  // ACE_Thread_Exit::instance ().  With the Xavier Pthreads package,
  // the exit_hook in TSS causes a seg fault.  So, this works around
  // that by creating exit_hook on the stack.
#if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)
  // Obtain our thread-specific exit hook and make sure that it knows
  // how to clean us up!  Note that we never use this pointer directly
  // (it's stored in thread-specific storage), so it's ok to
  // dereference it here and only store it as a reference.
  ACE_Thread_Exit &exit_hook = *ACE_Thread_Exit::instance ();
#else
  // Without TSS, create an <ACE_Thread_Exit> instance.  When this
  // function returns, its destructor will be called because the
  // object goes out of scope.  The drawback with this appraoch is
  // that the destructor _won't_ get called if <thr_exit> is called.
  // So, threads shouldn't exit that way.  Instead, they should return
  // from <svc>.
  ACE_Thread_Exit exit_hook;
#endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION */

  // Keep track of the <Thread_Manager> that's associated with this
  // <exit_hook>.
  exit_hook.thr_mgr (thread_args->thr_mgr ());

  // Invoke the user-supplied function with the args.
  void *status = thread_args->invoke ();

  return status;
}
#endif

// Call the appropriate OS routine to spawn a thread.  Should *not* be
// called with the lock_ held...

int
ACE_Thread_Manager::spawn_i (ACE_THR_FUNC func,
                             void *args,
                             long flags,
                             ACE_thread_t *t_id,
                             ACE_hthread_t *t_handle,
                             long priority,
                             int grp_id,
                             void *stack,
                             size_t stack_size,
                             ACE_Task_Base *task)
{
  // First, threads created by Thread Manager should not be daemon threads.
  // Using assertion is probably a bit too strong.  However, it helps
  // finding this kind of error as early as possible.  Perhaps we can replace
  // assertion by returning error.
  ACE_ASSERT (ACE_BIT_DISABLED (flags, THR_DAEMON));

  // Create a new thread running <func>.  *Must* be called with the
  // <lock_> held...
  // Get a "new" Thread Descriptor from the freelist.
  auto_ptr<ACE_Thread_Descriptor> new_thr_desc (this->thread_desc_freelist_.remove ());

  // Reset thread descriptor status
  new_thr_desc->reset (this);

  ACE_Thread_Adapter *thread_args = 0;
# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS)
  ACE_NEW_RETURN (thread_args,
                  ACE_Thread_Adapter (func,
                                      args,
                                      (ACE_THR_C_FUNC) ace_thread_adapter,
                                      this,
                                      new_thr_desc.get (),
                                      ACE_OS_Object_Manager::seh_except_selector(),
                                      ACE_OS_Object_Manager::seh_except_handler()),
                  -1);
#else
  ACE_NEW_RETURN (thread_args,
                  ACE_Thread_Adapter (func,
                                      args,
                                      (ACE_THR_C_FUNC) ace_thread_adapter,
                                      this,
                                      new_thr_desc.get ()),
                  -1);
# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */

  ACE_TRACE ("ACE_Thread_Manager::spawn_i");
  ACE_hthread_t thr_handle;

#if defined (VXWORKS)
  // On VxWorks, ACE_thread_t is char *.  If t_id is 0, allocate space
  // for ACE_OS::thr_create () to store the task name.  If t_id is not
  // 0, and it doesn't point to a 0 char *, then the non-zero char *
  // will be used for the task name in ACE_OS::thr_create ().  If t_id
  // is not 0, but does point to a 0 char *, the t_id will be set to
  // point to the task name in the TCB in ACE_OS::thr_create ().
  if (t_id == 0)
    {
      char *thr_id;
      ACE_NEW_RETURN (thr_id,
                      char[16],
                      -1);
      // Mark the thread ID to show that the ACE_Thread_Manager
      // allocated it.
      thr_id[0] = ACE_THR_ID_ALLOCATED;
      thr_id[1] = '\0';
      t_id = &thr_id;
    }
#else  /* ! VXWORKS */
  ACE_thread_t thr_id;
  if (t_id == 0)
    t_id = &thr_id;
#endif /* ! VXWORKS */

  new_thr_desc->sync_->acquire ();
  // Acquire the <sync_> lock to block the spawned thread from
  // removing this Thread Descriptor before it gets put into our
  // thread table.

  int result = ACE_Thread::spawn (func,
                                  args,
                                  flags,
                                  t_id,
                                  &thr_handle,
                                  priority,
                                  stack,
                                  stack_size,
                                  thread_args);

  if (result != 0)
    {
      // _Don't_ clobber errno here!  result is either 0 or -1, and
      // ACE_OS::thr_create () already set errno!  D. Levine 28 Mar 1997
      // errno = result;
      ACE_Errno_Guard guard (errno);     // Lock release may smash errno
      new_thr_desc->sync_->release ();
      return -1;
    }
  else
    {
#if defined (ACE_HAS_WTHREADS)
      // Have to duplicate handle if client asks for it.
      // @@ How are thread handles implemented on AIX?  Do they
      // also need to be duplicated?
      if (t_handle != 0)
# if defined (ACE_HAS_WINCE)
        *t_handle = thr_handle;
# else  /* ! ACE_HAS_WINCE */
        (void) ::DuplicateHandle (::GetCurrentProcess (),
                                  thr_handle,
                                  ::GetCurrentProcess (),
                                  t_handle,
                                  0,
                                  TRUE,
                                  DUPLICATE_SAME_ACCESS);
# endif /* ! ACE_HAS_WINCE */
#elif defined (VXWORKS)
     if (t_handle != 0)
       *t_handle = thr_handle;
#else  /* ! ACE_HAS_WTHREADS && ! VXWORKS */
      ACE_UNUSED_ARG (t_handle);
#endif /* ! ACE_HAS_WTHREADS && ! VXWORKS */

      // append_thr also put the <new_thr_desc> into Thread_Manager's
      // double-linked list.  Only after this point, can we manipulate
      // double-linked list from a spawned thread's context.
      return this->append_thr (*t_id,
                               thr_handle,
                               ACE_THR_SPAWNED,
                               grp_id,
                               task,
                               flags,
                               new_thr_desc.release ());
    }
}

int
ACE_Thread_Manager::spawn (ACE_THR_FUNC func,
                           void *args,
                           long flags,
                           ACE_thread_t *t_id,
                           ACE_hthread_t *t_handle,
                           long priority,
                           int grp_id,
                           void *stack,
                           size_t stack_size)
{
  ACE_TRACE ("ACE_Thread_Manager::spawn");

  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  if (grp_id == -1)
    grp_id = this->grp_id_++; // Increment the group id.

  if (this->spawn_i (func, args, flags, t_id, t_handle,
                     priority, grp_id, stack, stack_size) == -1)
    return -1;

  return grp_id;
}

// Create N new threads running FUNC.

int
ACE_Thread_Manager::spawn_n (size_t n,
                             ACE_THR_FUNC func,
                             void *args,
                             long flags,
                             long priority,
                             int grp_id,
                             ACE_Task_Base *task,
                             ACE_hthread_t thread_handles[],
                             void *stack[],
                             size_t stack_size[])
{
  ACE_TRACE ("ACE_Thread_Manager::spawn_n");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  if (grp_id == -1)
    grp_id = this->grp_id_++; // Increment the group id.

  for (size_t i = 0; i < n; i++)
    {
      // @@ What should happen if this fails?! e.g., should we try to
      // cancel the other threads that we've already spawned or what?
      if (this->spawn_i (func,
                         args,
                         flags,
                         0,
                         thread_handles == 0 ? 0 : &thread_handles[i],
                         priority,
                         grp_id,
                         stack == 0 ? 0 : stack[i],
                         stack_size == 0 ? 0 : stack_size[i],
                         task) == -1)
        return -1;
    }

  return grp_id;
}

// Create N new threads running FUNC.

int
ACE_Thread_Manager::spawn_n (ACE_thread_t thread_ids[],
                             size_t n,
                             ACE_THR_FUNC func,
                             void *args,
                             long flags,
                             long priority,
                             int grp_id,
                             void *stack[],
                             size_t stack_size[],
                             ACE_hthread_t thread_handles[],
                             ACE_Task_Base *task)
{
  ACE_TRACE ("ACE_Thread_Manager::spawn_n");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  if (grp_id == -1)
    grp_id = this->grp_id_++; // Increment the group id.

  for (size_t i = 0; i < n; i++)
    {
      // @@ What should happen if this fails?! e.g., should we try to
      // cancel the other threads that we've already spawned or what?
      if (this->spawn_i (func,
                         args,
                         flags,
                         thread_ids == 0 ? 0 : &thread_ids[i],
                         thread_handles == 0 ? 0 : &thread_handles[i],
                         priority,
                         grp_id,
                         stack == 0 ? 0 : stack[i],
                         stack_size == 0 ? 0 : stack_size[i],
                         task) == -1)
        return -1;
    }

  return grp_id;
}

// Append a thread into the pool (does not check for duplicates).
// Must be called with locks held.

int
ACE_Thread_Manager::append_thr (ACE_thread_t t_id,
                                ACE_hthread_t t_handle,
                                ACE_UINT32 thr_state,
                                int grp_id,
                                ACE_Task_Base *task,
                                long flags,
                                ACE_Thread_Descriptor *td)
{
  ACE_TRACE ("ACE_Thread_Manager::append_thr");
  ACE_Thread_Descriptor *thr_desc;

  if (td == 0)
    {
    ACE_NEW_RETURN (thr_desc,
                    ACE_Thread_Descriptor,
                    -1);
#if !defined(ACE_USE_ONE_SHOT_AT_THREAD_EXIT)
    thr_desc->tm_ = this;
    // Setup the Thread_Manager.
#endif /* !ACE_USE_ONE_SHOT_AT_THREAD_EXIT */
  }
  else
    thr_desc = td;

  thr_desc->thr_id_ = t_id;
  thr_desc->thr_handle_ = t_handle;
  thr_desc->grp_id_ = grp_id;
  thr_desc->task_ = task;
  thr_desc->flags_ = flags;

  this->thr_list_.insert_head (thr_desc);
  ACE_SET_BITS (thr_desc->thr_state_, thr_state);
  thr_desc->sync_->release ();

  return 0;
}

// Return the thread descriptor (indexed by ACE_hthread_t).

ACE_Thread_Descriptor *
ACE_Thread_Manager::find_hthread (ACE_hthread_t h_id)
{
  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (ACE_OS::thr_cmp (iter.next ()->thr_handle_, h_id))
      return iter.next ();

  return 0;
}

// Locate the index in the table associated with <t_id>.  Must be
// called with the lock held.

ACE_Thread_Descriptor *
ACE_Thread_Manager::find_thread (ACE_thread_t t_id)
{
  ACE_TRACE ("ACE_Thread_Manager::find_thread");

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (ACE_OS::thr_equal (iter.next ()->thr_id_, t_id))
      return iter.next ();
  return 0;
}

// Insert a thread into the pool (checks for duplicates and doesn't
// allow them to be inserted twice).

int
ACE_Thread_Manager::insert_thr (ACE_thread_t t_id,
                                ACE_hthread_t t_handle,
                                int grp_id,
                                long flags)
{
  ACE_TRACE ("ACE_Thread_Manager::insert_thr");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  // Check for duplicates and bail out if we're already registered...
#if defined (VXWORKS)
  if (this->find_hthread (t_handle) != 0 )
    return -1;
#else  /* ! VXWORKS */
  if (this->find_thread (t_id) != 0 )
    return -1;
#endif /* ! VXWORKS */

  if (grp_id == -1)
    grp_id = this->grp_id_++;

  if (this->append_thr (t_id,
                        t_handle,
                        ACE_THR_SPAWNED,
                        grp_id,
                        0,
                        flags) == -1)
    return -1;

  return grp_id;
}

// Run the registered hooks when the thread exits.

void
ACE_Thread_Manager::run_thread_exit_hooks (int i)
{
#if 0 // currently unused!
  ACE_TRACE ("ACE_Thread_Manager::run_thread_exit_hooks");

  // @@ Currently, we have just one hook.  This should clearly be
  // generalized to support an arbitrary number of hooks.

  ACE_Thread_Descriptor *td = this->thread_desc_self ();
  if (td != 0 && td->cleanup_info.cleanup_hook_ != 0)
    {
      (*td->cleanup_info_.cleanup_hook_)
        (td->cleanup_info_.object_,
         td->cleanup_info_.param_);

      td->cleanup_info_.cleanup_hook_ = 0;
    }
  ACE_UNUSED_ARG (i);
#else
  ACE_UNUSED_ARG (i);
#endif /* 0 */
}

// Remove a thread from the pool.  Must be called with locks held.

void
ACE_Thread_Manager::remove_thr (ACE_Thread_Descriptor *td,
                                int close_handler)
{
  ACE_TRACE ("ACE_Thread_Manager::remove_thr");

#if defined (VXWORKS)
  ACE_thread_t tid = td->self ();
#endif /* VXWORKS */

#if !defined(ACE_USE_ONE_SHOT_AT_THREAD_EXIT)
  td->tm_ = 0;
#endif /* !ACE_USE_ONE_SHOT_AT_THREAD_EXIT */
  this->thr_list_.remove (td);

#if defined (VXWORKS)
  // Delete the thread ID, if the ACE_Thread_Manager allocated it.
  if (tid  &&  tid[0] == ACE_THR_ID_ALLOCATED)
    {
      delete [] tid;
    }
#endif /* VXWORKS */

#if defined (ACE_WIN32)
  if (close_handler != 0)
    ::CloseHandle (td->thr_handle_);
#else
  ACE_UNUSED_ARG (close_handler);
#endif /* ACE_WIN32 */

#if 1

  this->thread_desc_freelist_.add (td);
#else
  delete td;
#endif /* 1 */

#if defined (ACE_HAS_THREADS)
  // Tell all waiters when there are no more threads left in the pool.
  if (this->thr_list_.size () == 0)
    this->zero_cond_.broadcast ();
#endif /* ACE_HAS_THREADS */
}

// Repeatedly call remove_thr on all table entries until there
// is no thread left.   Must be called with lock held.

void
ACE_Thread_Manager::remove_thr_all (void)
{
  ACE_Thread_Descriptor *td;

  while ((td = this->thr_list_.delete_head ()) != 0)
    {
#if defined (ACE_WIN32)
      // We need to let go handles if we want to let the threads
      // run wild.
      // @@ Do we need to close down AIX thread handles too?
      ::CloseHandle (td->thr_handle_);
#endif /* ACE_WIN32 */
      delete td;
    }

}

// ------------------------------------------------------------------
// Factor out some common behavior to simplify the following methods.
#define ACE_THR_OP(OP,STATE) \
  int result = OP (td->thr_handle_); \
  if (result == -1) { \
    if (errno != ENOTSUP) \
      this->thr_to_be_removed_.enqueue_tail (td); \
    return -1; \
  } \
  else { \
    ACE_SET_BITS (td->thr_state_, STATE); \
    return 0; \
  }

int
ACE_Thread_Manager::join_thr (ACE_Thread_Descriptor *td, int)
{
  ACE_TRACE ("ACE_Thread_Manager::join_thr");
  int result = ACE_Thread::join (td->thr_handle_);
  if (result != 0)
    {
      // Since the thread are being joined, we should
      // let it remove itself from the list.

      //      this->remove_thr (td);
      errno = result;
      return -1;
    }

  return 0;
}

int
ACE_Thread_Manager::suspend_thr (ACE_Thread_Descriptor *td, int)
{
  ACE_TRACE ("ACE_Thread_Manager::suspend_thr");

  int result = ACE_Thread::suspend (td->thr_handle_);
  if (result == -1) {
    if (errno != ENOTSUP)
      this->thr_to_be_removed_.enqueue_tail (td);
    return -1;
  }
  else {
    ACE_SET_BITS (td->thr_state_, ACE_THR_SUSPENDED);
    return 0;
  }
}

int
ACE_Thread_Manager::resume_thr (ACE_Thread_Descriptor *td, int)
{
  ACE_TRACE ("ACE_Thread_Manager::resume_thr");

  int result = ACE_Thread::resume (td->thr_handle_);
  if (result == -1) {
    if (errno != ENOTSUP)
      this->thr_to_be_removed_.enqueue_tail (td);
    return -1;
  }
  else {
    ACE_CLR_BITS (td->thr_state_, ACE_THR_SUSPENDED);
    return 0;
  }
}

int
ACE_Thread_Manager::cancel_thr (ACE_Thread_Descriptor *td, int async_cancel)
{
  ACE_TRACE ("ACE_Thread_Manager::cancel_thr");
  // Must set the state first and then try to cancel the thread.
  ACE_SET_BITS (td->thr_state_, ACE_THR_CANCELLED);

  if (async_cancel != 0)
    // Note that this call only does something relevant if the OS
    // platform supports asynchronous thread cancellation.  Otherwise,
    // it's a no-op.
    return ACE_Thread::cancel (td->thr_id_);

  return 0;
}

int
ACE_Thread_Manager::kill_thr (ACE_Thread_Descriptor *td, int signum)
{
  ACE_TRACE ("ACE_Thread_Manager::kill_thr");

  ACE_thread_t tid = td->thr_id_;
#if defined (VXWORKS)
  // Skip over the ID-allocated marker, if present.
  tid += tid[0] == ACE_THR_ID_ALLOCATED  ?  1  :  0;
#endif /* VXWORKS */

  int result = ACE_Thread::kill (tid, signum);

  if (result != 0)
    {
      // Only remove a thread from us when there is a "real" error.
      if (errno != ENOTSUP)
        this->thr_to_be_removed_.enqueue_tail (td);

      return -1;
    }
#if defined (CHORUS)
  else if (signum == SIGTHREADKILL)
    this->thr_to_be_removed_.enqueue_tail (td);
#endif /* CHORUS */

    return 0;
}

// ------------------------------------------------------------------
// Factor out some common behavior to simplify the following methods.
#define ACE_EXECUTE_OP(OP, ARG) \
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); \
  ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); \
  ACE_FIND (this->find_thread (t_id), ptr); \
  if (ptr == 0) \
    { \
      errno = ENOENT; \
      return -1; \
    } \
  int result = OP (ptr, ARG); \
  ACE_Errno_Guard error (errno); \
  while (! this->thr_to_be_removed_.is_empty ()) { \
    ACE_Thread_Descriptor *td; \
    this->thr_to_be_removed_.dequeue_head (td); \
    this->remove_thr (td, 1); \
  } \
  return result

// Suspend a single thread.

int
ACE_Thread_Manager::suspend (ACE_thread_t t_id)
{
  ACE_TRACE ("ACE_Thread_Manager::suspend");
  ACE_EXECUTE_OP (this->suspend_thr, 0);
}

// Resume a single thread.

int
ACE_Thread_Manager::resume (ACE_thread_t t_id)
{
  ACE_TRACE ("ACE_Thread_Manager::resume");
  ACE_EXECUTE_OP (this->resume_thr, 0);
}

// Cancel a single thread.

int
ACE_Thread_Manager::cancel (ACE_thread_t t_id, int async_cancel)
{
  ACE_TRACE ("ACE_Thread_Manager::cancel");
  ACE_EXECUTE_OP (this->cancel_thr, async_cancel);
}

// Send a signal to a single thread.

int
ACE_Thread_Manager::kill (ACE_thread_t t_id, int signum)
{
  ACE_TRACE ("ACE_Thread_Manager::kill");
  ACE_EXECUTE_OP (this->kill_thr, signum);
}

int
ACE_Thread_Manager::check_state (ACE_UINT32 state,
                                 ACE_thread_t id,
                                 int enable)
{
  ACE_TRACE ("ACE_Thread_Manager::check_state");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  ACE_UINT32 thr_state;

  int self_check = ACE_OS::thr_equal (id, ACE_OS::thr_self ());

  // If we're checking the state of our thread, try to get the cached
  // value out of TSS to avoid lookup.
  if (self_check)
    thr_state = this->thread_desc_self ()->thr_state_;
  else
    {
      // Not calling from self, have to look it up from the list.
      ACE_FIND (this->find_thread (id), ptr);
      if (ptr == 0)
        return 0;
      thr_state = ptr->thr_state_;
    }
  if (enable)
    return ACE_BIT_ENABLED (thr_state, state);

  return ACE_BIT_DISABLED (thr_state, state);
}

// Test if a single thread is suspended.

int
ACE_Thread_Manager::testsuspend (ACE_thread_t t_id)
{
  ACE_TRACE ("ACE_Thread_Manager::testsuspend");
  return this->check_state (ACE_THR_SUSPENDED, t_id);
}

// Test if a single thread is active (i.e., resumed).

int
ACE_Thread_Manager::testresume (ACE_thread_t t_id)
{
  ACE_TRACE ("ACE_Thread_Manager::testresume");
  return this->check_state (ACE_THR_SUSPENDED, t_id, 0);
}

// Test if a single thread is cancelled.

int
ACE_Thread_Manager::testcancel (ACE_thread_t t_id)
{
  ACE_TRACE ("ACE_Thread_Manager::testcancel");
  return this->check_state (ACE_THR_CANCELLED, t_id);
}

// Thread information query functions.

int
ACE_Thread_Manager::hthread_within (ACE_hthread_t handle)
{
  ACE_TRACE ("ACE_Thread_Manager::hthread_within");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1));

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (ACE_OS::thr_cmp(iter.next ()->thr_handle_, handle))
      return 1;

  return 0;
}

int
ACE_Thread_Manager::thread_within (ACE_thread_t tid)
{
  ACE_TRACE ("ACE_Thread_Manager::thread_within");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1));

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (ACE_OS::thr_equal (iter.next ()->thr_id_, tid))
      return 1;

  return 0;
}

// Get group ids for a particular thread id.

int
ACE_Thread_Manager::get_grp (ACE_thread_t t_id, int &grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::get_grp");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  ACE_FIND (this->find_thread (t_id), ptr);

  if (ptr)
    grp_id = ptr->grp_id_;
  else
    return -1;
  return 0;
}

// Set group ids for a particular thread id.

int
ACE_Thread_Manager::set_grp (ACE_thread_t t_id, int grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::set_grp");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  ACE_FIND (this->find_thread (t_id), ptr);
  if (ptr)
    ptr->grp_id_ = grp_id;
  else
    return -1;
  return 0;
}

// Suspend a group of threads.

int
ACE_Thread_Manager::apply_grp (int grp_id,
                               ACE_THR_MEMBER_FUNC func,
                               int arg)
{
  ACE_TRACE ("ACE_Thread_Manager::apply_grp");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1));
  ACE_ASSERT (this->thr_to_be_removed_.is_empty ());

  int result = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (iter.next ()->grp_id_ == grp_id)
      if ((this->*func) (iter.next (), arg) == -1)
        result = -1;

  // Must remove threads after we have traversed the thr_list_ to
  // prevent clobber thr_list_'s integrity.

  if (! this->thr_to_be_removed_.is_empty ())
    {
      // Save/restore errno.
      ACE_Errno_Guard error (errno);

      for (ACE_Thread_Descriptor *td;
           this->thr_to_be_removed_.dequeue_head (td) != -1;
           )
        this->remove_thr (td, 1);
    }

  return result;
}

int
ACE_Thread_Manager::suspend_grp (int grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::suspend_grp");
  return this->apply_grp (grp_id,
                          ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr));
}

// Resume a group of threads.

int
ACE_Thread_Manager::resume_grp (int grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::resume_grp");
  return this->apply_grp (grp_id,
                          ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr));
}

// Kill a group of threads.

int
ACE_Thread_Manager::kill_grp (int grp_id, int signum)
{
  ACE_TRACE ("ACE_Thread_Manager::kill_grp");
  return this->apply_grp (grp_id,
                          ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::kill_thr), signum);
}

// Cancel a group of threads.

int
ACE_Thread_Manager::cancel_grp (int grp_id, int async_cancel)
{
  ACE_TRACE ("ACE_Thread_Manager::cancel_grp");
  return this->apply_grp (grp_id,
                          ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr),
                          async_cancel);
}

int
ACE_Thread_Manager::apply_all (ACE_THR_MEMBER_FUNC func, int arg)
{
  ACE_TRACE ("ACE_Thread_Manager::apply_all");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));
  ACE_ASSERT (this->thr_to_be_removed_.is_empty ());

  int result = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if ((this->*func)(iter.next (), arg) == -1)
      result = -1;

  // Must remove threads after we have traversed the thr_list_ to
  // prevent clobber thr_list_'s integrity.

  if (! this->thr_to_be_removed_.is_empty ())
    {
      // Save/restore errno.
      ACE_Errno_Guard error (errno);

      for (ACE_Thread_Descriptor *td;
           this->thr_to_be_removed_.dequeue_head (td) != -1;
           )
        this->remove_thr (td, 1);
    }

  return result;
}

// Resume all threads that are suspended.

int
ACE_Thread_Manager::resume_all (void)
{
  ACE_TRACE ("ACE_Thread_Manager::resume_all");
  return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr));
}

int
ACE_Thread_Manager::suspend_all (void)
{
  ACE_TRACE ("ACE_Thread_Manager::suspend_all");
  return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr));
}

int
ACE_Thread_Manager::kill_all (int sig)
{
  ACE_TRACE ("ACE_Thread_Manager::kill_all");
  return this->apply_all (&ACE_Thread_Manager::kill_thr, sig);
}

int
ACE_Thread_Manager::cancel_all (int async_cancel)
{
  ACE_TRACE ("ACE_Thread_Manager::cancel_all");
  return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr),
                          async_cancel);
}

int
ACE_Thread_Manager::join (ACE_thread_t tid, ACE_THR_FUNC_RETURN *status)
{
  ACE_TRACE ("ACE_Thread_Manager::join");

  ACE_Thread_Descriptor_Base tdb;
  int found = 0;

  {
    ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

#if !defined (VXWORKS)
    for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor_Base> biter (this->terminated_thr_list_);
         !biter.done ();
         biter.advance ())
      if (ACE_OS::thr_equal (biter.next ()->thr_id_, tid))
        {
          ACE_Thread_Descriptor_Base *tdb = biter.advance_and_remove (0);
          if (ACE_Thread::join (tdb->thr_handle_) == -1)
            return -1;

# if defined (ACE_HAS_PTHREADS_DRAFT4)  &&  defined (ACE_LACKS_SETDETACH)
          // Must explicitly detach threads.  Threads without THR_DETACHED
          // were detached in ACE_OS::thr_create ().
          ::pthread_detach (&tdb->thr_handle_);
# endif /* ACE_HAS_PTHREADS_DRAFT4 && ACE_LACKS_SETDETACH */

          delete tdb;
          return 0;
          // return immediately if we've found the thread we want to join.
        }
#endif /* !VXWORKS */

    for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
         !iter.done ();
         iter.advance ())
      // If threads are created as THR_DETACHED or THR_DAEMON, we
      // can't help much.
      if (ACE_OS::thr_equal (iter.next ()->thr_id_,tid) &&
          (ACE_BIT_DISABLED (iter.next ()->flags_, THR_DETACHED | THR_DAEMON)
           || ACE_BIT_ENABLED (iter.next ()->flags_, THR_JOINABLE)))
        {
          tdb = *iter.next ();
          ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING);
          found = 1;
          break;
        }

    if (found == 0)
      return -1;
    // Didn't find the thread we want or the thread is not joinable.
  }

# if defined (_AIX)
  // The AIX xlC compiler does not match the proper function here - it
  // confuses ACE_Thread::join(ACE_thread_t, ACE_thread_t *, void **=0) and
  // ACE_Thread::join(ACE_hthread_t, void **=0).  At least at 3.1.4.7 and .8.
  // The 2nd arg is ignored for pthreads anyway.

  // And, g++ on AIX needs the three-arg thr_join, also, to pick up the
  // proper version from the AIX libraries.
  if (ACE_Thread::join (tdb.thr_handle_, &tdb.thr_handle_, status) == -1)
# else  /* ! _AIX */
  if (ACE_Thread::join (tdb.thr_handle_, status) == -1)
# endif /* ! _AIX */
    return -1;

# if defined (ACE_HAS_PTHREADS_DRAFT4)  &&  defined (ACE_LACKS_SETDETACH)
  // Must explicitly detach threads.  Threads without THR_DETACHED
  // were detached in ACE_OS::thr_create ().

#   if defined (HPUX_10)
  // HP-UX DCE threads' pthread_detach will smash thr_id if it's just given
  // as an argument.  Since the thread handle is still needed, give
  // pthread_detach a junker to scribble on.
  ACE_thread_t  junker;
  cma_handle_assign(&tdb.thr_handle_, &junker);
  ::pthread_detach (&junker);
#   else
  ::pthread_detach (&tdb.thr_handle_);
    #endif /* HPUX_10 */
# endif /* ACE_HAS_PTHREADS_DRAFT4 && ACE_LACKS_SETDETACH */
  return 0;
}

// Wait for group of threads

int
ACE_Thread_Manager::wait_grp (int grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::wait_grp");

  int copy_count = 0;
  ACE_Thread_Descriptor_Base *copy_table = 0;

  // We have to make sure that while we wait for these threads to
  // exit, we do not have the lock.  Therefore we make a copy of all
  // interesting entries and let go of the lock.
  {
    ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

#if !defined (VXWORKS)
    ACE_NEW_RETURN (copy_table,
                    ACE_Thread_Descriptor_Base [this->thr_list_.size ()
                                               + this->terminated_thr_list_.size ()],
                    -1);
#else
    ACE_NEW_RETURN (copy_table,
                    ACE_Thread_Descriptor_Base [this->thr_list_.size ()],
                    -1);
#endif /* VXWORKS */

    for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
         !iter.done ();
         iter.advance ())
      // If threads are created as THR_DETACHED or THR_DAEMON, we
      // can't help much.
      if (iter.next ()->grp_id_ == grp_id &&
          (ACE_BIT_DISABLED (iter.next ()->flags_, THR_DETACHED | THR_DAEMON)
           || ACE_BIT_ENABLED (iter.next ()->flags_, THR_JOINABLE)))
        {
          ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING);
          copy_table[copy_count++] = *iter.next ();
        }

#if !defined (VXWORKS)
    for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor_Base> biter (this->terminated_thr_list_);
         !biter.done ();
         biter.advance ())
      // If threads are created as THR_DETACHED or THR_DAEMON, we
      // can't help much.
      if (biter.next ()->grp_id_ == grp_id)
        {
          ACE_Thread_Descriptor_Base *tdb = biter.advance_and_remove (0);
          copy_table[copy_count++] = *tdb;
          delete tdb;
        }
#endif /* !VXWORKS */
  }

  // Now actually join() with all the threads in this group.
  int result = 0;

  for (int i = 0;
       i < copy_count && result != -1;
       i++)
    {
      if (ACE_Thread::join (copy_table[i].thr_handle_) == -1)
        result = -1;

# if defined (ACE_HAS_PTHREADS_DRAFT4)  &&  defined (ACE_LACKS_SETDETACH)
      // Must explicitly detach threads.  Threads without THR_DETACHED
      // were detached in ACE_OS::thr_create ().
      ::pthread_detach (&copy_table[i].thr_handle_);
# endif /* ACE_HAS_PTHREADS_DRAFT4 && ACE_LACKS_SETDETACH */
    }

  delete [] copy_table;

  return result;
}

// Must be called when thread goes out of scope to clean up its table
// slot.

ACE_THR_FUNC_RETURN
ACE_Thread_Manager::exit (ACE_THR_FUNC_RETURN status, int do_thr_exit)
{
  ACE_TRACE ("ACE_Thread_Manager::exit");
#if defined(ACE_USE_ONE_SHOT_AT_THREAD_EXIT)
  int close_handle = 0;
#endif /* ACE_USE_ONE_SHOT_AT_THREAD_EXIT */

#if defined (ACE_WIN32)
  // Remove detached thread handle.

  if (do_thr_exit)
    {
#if 0
      // @@ This callback is now taken care of by TSS_Cleanup.  Do we
      //    need it anymore?

      // On Win32, if we really wants to exit from a thread, we must
      // first  clean up the thread specific storage.  By doing so,
      // ACE_Thread_Manager::exit will be called again with
      // do_thr_exit = 0 and cleaning up the ACE_Cleanup_Info (but not
      // exiting the thread.)  After the following call returns, we
      // are safe to exit this thread.
      delete ACE_Thread_Exit::instance ();
#endif /* 0 */
      ACE_Thread::exit (status);
    }
#endif /* ACE_WIN32 */

#if defined(ACE_USE_ONE_SHOT_AT_THREAD_EXIT)
  ACE_Cleanup_Info cleanup_info;

  // Just hold onto the guard while finding this thread's id and
  // copying the exit hook.
  {
    ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));

    // Find the thread id, but don't use the cache.  It might have been
    // deleted already.
#if defined (VXWORKS)
    ACE_hthread_t id;
    ACE_OS::thr_self (id);
    ACE_Thread_Descriptor *td = this->find_hthread (id);
#else  /* ! VXWORKS */
    ACE_thread_t id = ACE_OS::thr_self ();
    ACE_Thread_Descriptor *td = this->find_thread (id);
#endif /* ! VXWORKS */

    // Locate thread id.
    if (td != 0)
      {
        // @@ Currently, we have just one hook.  This should clearly
        // be generalized to support an arbitrary number of hooks.

        if (td->cleanup_info_.cleanup_hook_ != 0)
          {
            // Copy the hook so that we can call it after releasing
            // the guard.
            cleanup_info = td->cleanup_info_;
            td->cleanup_info_.cleanup_hook_ = 0;
          }

#if !defined (VXWORKS)
        // Threads created with THR_DAEMON shouldn't exist here, but
        // just to be safe, let's put it here.

        if (ACE_BIT_DISABLED (td->thr_state_, ACE_THR_JOINING))
          if (ACE_BIT_DISABLED (td->flags_, THR_DETACHED | THR_DAEMON)
              || ACE_BIT_ENABLED (td->flags_, THR_JOINABLE))
            {
              // Mark thread as terminated.
              ACE_SET_BITS (td->thr_state_, ACE_THR_TERMINATED);
              this->register_as_terminated (td);
              // Must copy the information here because td will be "freed" below.
            }
#if defined (ACE_WIN32)
          else
            {
              close_handle = 1;
            }
#endif /* ACE_WIN32 */
#endif /* ! VXWORKS */

        // Remove thread descriptor from the table.
        this->remove_thr (td, close_handle);
      }
    // Release the guard.
  }

  // Call the cleanup hook.
  if (cleanup_info.cleanup_hook_ != 0)
    (*cleanup_info.cleanup_hook_) (cleanup_info.object_,
                                   cleanup_info.param_);
#else /* !ACE_USE_ONE_SHOT_AT_THREAD_EXIT */
  // Just hold onto the guard while finding this thread's id and
  {
    ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));

    // Find the thread id, but don't use the cache.  It might have been
    // deleted already.
#if defined (VXWORKS)
    ACE_hthread_t id;
    ACE_OS::thr_self (id);
    ACE_Thread_Descriptor* td = this->find_hthread (id);
#else  /* ! VXWORKS */
    ACE_thread_t id = ACE_OS::thr_self ();
    ACE_Thread_Descriptor* td = this->find_thread (id);
#endif /* ! VXWORKS */
    if (td != 0)
     {
       // @@ We call Thread_Descriptor terminate this realize the cleanup
       // process itself.
       td->terminate();
     }
  }


#endif /* !ACE_USE_ONE_SHOT_AT_THREAD_EXIT */

  if (do_thr_exit)
    {
      ACE_Thread::exit (status);
      // On reasonable systems <ACE_Thread::exit> should not return.
      // However, due to horrible semantics with Win32 thread-specific
      // storage this call can return (don't ask...).
    }

  return 0;
}

// Wait for all the threads to exit.

int
ACE_Thread_Manager::wait (const ACE_Time_Value *timeout,
                          int abandon_detached_threads)
{
  ACE_TRACE ("ACE_Thread_Manager::wait");

#if defined (ACE_HAS_THREADS)
  {
    // Just hold onto the guard while waiting.
    ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

    if (ACE_Object_Manager::shutting_down () != 1)
      {
        // Program is not shutting down.  Perform a normal wait on threads.
        if (abandon_detached_threads != 0)
          {
            ACE_ASSERT (this->thr_to_be_removed_.is_empty ());
            for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor>
                   iter (this->thr_list_);
                 !iter.done ();
                 iter.advance ())
              if (ACE_BIT_ENABLED (iter.next ()->flags_,
                                   THR_DETACHED | THR_DAEMON)
                  && ACE_BIT_DISABLED (iter.next ()->flags_, THR_JOINABLE))
                {
                  this->thr_to_be_removed_.enqueue_tail (iter.next ());
                  ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING);
                }

            if (! this->thr_to_be_removed_.is_empty ())
              {
                ACE_Thread_Descriptor *td;
                while (this->thr_to_be_removed_.dequeue_head (td) != -1)
                  this->remove_thr (td, 1);
              }
          }

        while (this->thr_list_.size () > 0)
          if (this->zero_cond_.wait (timeout) == -1)
            return -1;
      }
    else
        // Program is shutting down, no chance to wait on threads.
        // Therefore, we'll just remove threads from the list.
        this->remove_thr_all ();
    // Release the guard, giving other threads a chance to run.
  }

#if !defined (VXWORKS)
  // @@ VxWorks doesn't support thr_join (yet.)  We are working
  //on our implementation.   Chorus'es thr_join seems broken.
  ACE_Thread_Descriptor_Base *item;

#if defined (CHORUS)
  if (ACE_Object_Manager::shutting_down () != 1)
    {
#endif /* CHORUS */
      while ((item = this->terminated_thr_list_.delete_head ()) != 0)
        {
          if (ACE_BIT_DISABLED (item->flags_, THR_DETACHED | THR_DAEMON)
              || ACE_BIT_ENABLED (item->flags_, THR_JOINABLE))
            // Detached handles shouldn't reached here.
              ACE_Thread::join (item->thr_handle_);

# if defined (ACE_HAS_PTHREADS_DRAFT4)  &&  defined (ACE_LACKS_SETDETACH)
          // Must explicitly detach threads.  Threads without
          // THR_DETACHED were detached in ACE_OS::thr_create ().
          ::pthread_detach (&item->thr_handle_);
# endif /* ACE_HAS_PTHREADS_DRAFT4 && ACE_LACKS_SETDETACH */
          delete item;
        }
#if defined (CHORUS)
    }
#endif /* CHORUS */

#endif /* ! VXWORKS */
#else
  ACE_UNUSED_ARG (timeout);
  ACE_UNUSED_ARG (abandon_detached_threads);
#endif /* ACE_HAS_THREADS */

  return 0;
}

int
ACE_Thread_Manager::apply_task (ACE_Task_Base *task,
                                ACE_THR_MEMBER_FUNC func,
                                int arg)
{
  ACE_TRACE ("ACE_Thread_Manager::apply_task");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));
  ACE_ASSERT (this->thr_to_be_removed_.is_empty ());

  int result = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (iter.next ()->task_ == task
        && (this->*func) (iter.next (), arg) == -1)
      result = -1;

  // Must remove threads after we have traversed the thr_list_ to
  // prevent clobber thr_list_'s integrity.

  if (! this->thr_to_be_removed_.is_empty ())
    {
      // Save/restore errno.
      ACE_Errno_Guard error (errno);

      for (ACE_Thread_Descriptor *td;
           this->thr_to_be_removed_.dequeue_head (td) != -1;
           )
        this->remove_thr (td, 1);
    }

  return result;
}

// Wait for all threads to exit a task.

int
ACE_Thread_Manager::wait_task (ACE_Task_Base *task)
{
  int copy_count = 0;
  ACE_Thread_Descriptor_Base *copy_table = 0;

  // We have to make sure that while we wait for these threads to
  // exit, we do not have the lock.  Therefore we make a copy of all
  // interesting entries and let go of the lock.
  {
    ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

#if !defined (VXWORKS)
    ACE_NEW_RETURN (copy_table,
                    ACE_Thread_Descriptor_Base [this->thr_list_.size ()
                                                + this->terminated_thr_list_.size ()],
                    -1);
#else
    ACE_NEW_RETURN (copy_table,
                    ACE_Thread_Descriptor_Base [this->thr_list_.size ()],
                    -1);
#endif /* VXWORKS */

    for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
         !iter.done ();
         iter.advance ())
      // If threads are created as THR_DETACHED or THR_DAEMON, we
      // can't wait on them here.
      if (iter.next ()->task_ == task &&
          (ACE_BIT_DISABLED (iter.next ()->flags_,
                             THR_DETACHED | THR_DAEMON)
           || ACE_BIT_ENABLED (iter.next ()->flags_,
                               THR_JOINABLE)))
        {
          ACE_SET_BITS (iter.next ()->thr_state_,
                        ACE_THR_JOINING);
          copy_table[copy_count++] = *iter.next ();
        }

#if !defined (VXWORKS)
    for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor_Base> titer (this->terminated_thr_list_);
         !titer.done ();
         titer.advance ())
      // If threads are created as THR_DETACHED or THR_DAEMON, we can't help much here.
      if (titer.next ()->task_ == task)
        {
          ACE_Thread_Descriptor_Base *tdb =
            titer.advance_and_remove (0);
          copy_table[copy_count++] = *tdb;
          delete tdb;
        }
#endif /* VXWORKS */
  }

  // Now to do the actual work
  int result = 0;

  for (int i = 0;
       i < copy_count && result != -1;
       i++)
    {
      if (ACE_Thread::join (copy_table[i].thr_handle_) == -1)
        result = -1;

# if defined (ACE_HAS_PTHREADS_DRAFT4)  &&  defined (ACE_LACKS_SETDETACH)
      // Must explicitly detach threads.  Threads without THR_DETACHED
      // were detached in ACE_OS::thr_create ().
      ::pthread_detach (&copy_table[i].thr_handle_);
# endif /* ACE_HAS_PTHREADS_DRAFT4 && ACE_LACKS_SETDETACH */
    }

  delete [] copy_table;

  return result;
}

// Suspend a task

int
ACE_Thread_Manager::suspend_task (ACE_Task_Base *task)
{
  ACE_TRACE ("ACE_Thread_Manager::suspend_task");
  return this->apply_task (task,
                           ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr));
}

// Resume a task.
int
ACE_Thread_Manager::resume_task (ACE_Task_Base *task)
{
  ACE_TRACE ("ACE_Thread_Manager::resume_task");
  return this->apply_task (task,
                           ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr));
}

// Kill a task.

int
ACE_Thread_Manager::kill_task (ACE_Task_Base *task, int /* signum */)
{
  ACE_TRACE ("ACE_Thread_Manager::kill_task");
  return this->apply_task (task,
                           ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::kill_thr));
}

// Cancel a task.
int
ACE_Thread_Manager::cancel_task (ACE_Task_Base *task,
                                 int async_cancel)
{
  ACE_TRACE ("ACE_Thread_Manager::cancel_task");
  return this->apply_task (task,
                           ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr),
                           async_cancel);
}

// Locate the index in the table associated with <task> from the
// beginning of the table up to an index.  Must be called with the
// lock held.

ACE_Thread_Descriptor *
ACE_Thread_Manager::find_task (ACE_Task_Base *task, int slot)
{
  ACE_TRACE ("ACE_Thread_Manager::find_task");

  int i = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (i >= slot)
        break;

      if (task == iter.next ()->task_)
        return iter.next ();

      i++;
    }

  return 0;
}

// Returns the number of ACE_Task in a group.

int
ACE_Thread_Manager::num_tasks_in_group (int grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::num_tasks_in_group");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  int tasks_count = 0;
  size_t i = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (iter.next ()->grp_id_ == grp_id
          && this->find_task (iter.next ()->task_, i) == 0
          && iter.next ()->task_ != 0)
        tasks_count++;

      i++;
    }
  return tasks_count;
}

// Returns the number of threads in an ACE_Task.

int
ACE_Thread_Manager::num_threads_in_task (ACE_Task_Base *task)
{
  ACE_TRACE ("ACE_Thread_Manager::num_threads_in_task");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  int threads_count = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (iter.next ()->task_ == task)
      threads_count++;

  return threads_count;
}

// Returns in task_list a list of ACE_Tasks registered with ACE_Thread_Manager.

int
ACE_Thread_Manager::task_all_list (ACE_Task_Base *task_list[],
                                   size_t n)
{
  ACE_TRACE ("ACE_Thread_Manager::task_all_list");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  size_t task_list_count = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (task_list_count >= n)
        break;

      ACE_Task_Base *task_p = iter.next ()->task_;
      if (0 != task_p)
        {
          // This thread has a task pointer; see if it's already in the
          // list. Don't add duplicates.
          size_t i = 0;
          for (; i < task_list_count; ++i)
            if (task_list[i] == task_p)
              break;
          if (i == task_list_count)        // No match - add this one
            task_list[task_list_count++] = task_p;
        }
    }

  return task_list_count;
}

// Returns in thread_list a list of all thread ids

int
ACE_Thread_Manager::thread_all_list ( ACE_thread_t thread_list[],
                                      size_t n)
{
  ACE_TRACE ("ACE_Thread_Manager::thread_all_list");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  size_t thread_count = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (thread_count >= n)
        break;

      thread_list[thread_count] = iter.next ()->thr_id_;
      thread_count ++;
    }

  return thread_count;
}

// Returns in task_list a list of ACE_Tasks in a group.

int
ACE_Thread_Manager::task_list (int grp_id,
                               ACE_Task_Base *task_list[],
                               size_t n)
{
  ACE_TRACE ("ACE_Thread_Manager::task_list");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  ACE_Task_Base **task_list_iterator = task_list;
  size_t task_list_count = 0;
  size_t i = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (task_list_count >= n)
        break;

      if (iter.next ()->grp_id_ == grp_id
          && this->find_task (iter.next ()->task_, i) == 0)
        {
          task_list_iterator[task_list_count] = iter.next ()->task_;
          task_list_count++;
        }

      i++;
    }

  return task_list_count;
}

// Returns in thread_list a list of thread ids in an ACE_Task.

int
ACE_Thread_Manager::thread_list (ACE_Task_Base *task,
                                 ACE_thread_t thread_list[],
                                 size_t n)
{
  ACE_TRACE ("ACE_Thread_Manager::thread_list");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  size_t thread_count = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (thread_count >= n)
        break;

      if (iter.next ()->task_ == task)
        {
          thread_list[thread_count] = iter.next ()->thr_id_;
          thread_count++;
        }
    }

  return thread_count;
}

// Returns in thread_list a list of thread handles in an ACE_Task.

int
ACE_Thread_Manager::hthread_list (ACE_Task_Base *task,
                                  ACE_hthread_t hthread_list[],
                                  size_t n)
{
  ACE_TRACE ("ACE_Thread_Manager::hthread_list");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  size_t hthread_count = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (hthread_count >= n)
        break;

      if (iter.next ()->task_ == task)
        {
          hthread_list[hthread_count] = iter.next ()->thr_handle_;
          hthread_count++;
        }
    }

  return hthread_count;
}

int
ACE_Thread_Manager::thread_grp_list (int grp_id,
                                     ACE_thread_t thread_list[],
                                     size_t n)
{
  ACE_TRACE ("ACE_Thread_Manager::thread_grp_list");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  size_t thread_count = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (thread_count >= n)
        break;

      if (iter.next ()->grp_id_ == grp_id)
        {
          thread_list[thread_count] = iter.next ()->thr_id_;
          thread_count++;
        }
    }

  return thread_count;
}

// Returns in thread_list a list of thread handles in an ACE_Task.

int
ACE_Thread_Manager::hthread_grp_list (int grp_id,
                                      ACE_hthread_t hthread_list[],
                                      size_t n)
{
  ACE_TRACE ("ACE_Thread_Manager::hthread_grp_list");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  size_t hthread_count = 0;

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    {
      if (hthread_count >= n)
        break;

      if (iter.next ()->grp_id_ == grp_id)
        {
          hthread_list[hthread_count] = iter.next ()->thr_handle_;
          hthread_count++;
        }
    }

  return hthread_count;
}

int
ACE_Thread_Manager::set_grp (ACE_Task_Base *task, int grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::set_grp");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  for (ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor> iter (this->thr_list_);
       !iter.done ();
       iter.advance ())
    if (iter.next ()->task_ == task)
      iter.next ()->grp_id_ = grp_id;

  return 0;
}

int
ACE_Thread_Manager::get_grp (ACE_Task_Base *task, int &grp_id)
{
  ACE_TRACE ("ACE_Thread_Manager::get_grp");
  ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1));

  ACE_FIND (this->find_task (task), ptr);
  grp_id = ptr->grp_id_;
  return 0;
}

#if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION)
# if defined (ACE_THREAD_MANAGER_LACKS_STATICS)
template class ACE_Singleton<ACE_Thread_Manager, ACE_SYNCH_MUTEX>;
# endif /* defined (ACE_THREAD_MANAGER_LACKS_STATICS) */
#  if defined (ACE_LACKS_AUTO_PTR) \
      || !(defined (ACE_HAS_STANDARD_CPP_LIBRARY) \
           && (ACE_HAS_STANDARD_CPP_LIBRARY != 0))
template class ACE_Auto_Basic_Ptr<ACE_Thread_Descriptor>;
#  endif  /* ACE_LACKS_AUTO_PTR */
template class auto_ptr<ACE_Thread_Descriptor>;
template class ACE_Double_Linked_List<ACE_Thread_Descriptor_Base>;
template class ACE_Double_Linked_List_Iterator_Base<ACE_Thread_Descriptor_Base>;
template class ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor_Base>;
template class ACE_Double_Linked_List<ACE_Thread_Descriptor>;
template class ACE_Double_Linked_List_Iterator_Base<ACE_Thread_Descriptor>;
template class ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor>;
template class ACE_Node<ACE_Thread_Descriptor*>;
template class ACE_Unbounded_Queue<ACE_Thread_Descriptor*>;
template class ACE_Unbounded_Queue_Iterator<ACE_Thread_Descriptor*>;
template class ACE_Free_List<ACE_Thread_Descriptor>;
template class ACE_Locked_Free_List<ACE_Thread_Descriptor, ACE_DEFAULT_THREAD_MANAGER_LOCK>;
#elif defined (ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA)
#  if defined (ACE_THREAD_MANAGER_LACKS_STATICS)
#    pragma instantiate ACE_Singleton<ACE_Thread_Manager, ACE_SYNCH_MUTEX>
#   endif /* defined (ACE_THREAD_MANAGER_LACKS_STATICS) */

#  if defined (ACE_LACKS_AUTO_PTR) \
      || !(defined (ACE_HAS_STANDARD_CPP_LIBRARY) \
           && (ACE_HAS_STANDARD_CPP_LIBRARY != 0))
#    pragma instantiate ACE_Auto_Basic_Ptr<ACE_Thread_Descriptor>
#  endif  /* ACE_LACKS_AUTO_PTR */
#  pragma instantiate auto_ptr<ACE_Thread_Descriptor>
#  pragma instantiate ACE_Double_Linked_List<ACE_Thread_Descriptor_Base>
#  pragma instantiate ACE_Double_Linked_List_Iterator_Base<ACE_Thread_Descriptor_Base>
#  pragma instantiate ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor_Base>
#  pragma instantiate ACE_Double_Linked_List<ACE_Thread_Descriptor>
#  pragma instantiate ACE_Double_Linked_List_Iterator_Base<ACE_Thread_Descriptor>
#  pragma instantiate ACE_Double_Linked_List_Iterator<ACE_Thread_Descriptor>
#  pragma instantiate ACE_Node<ACE_Thread_Descriptor*>
#  pragma instantiate ACE_Unbounded_Queue<ACE_Thread_Descriptor*>
#  pragma instantiate ACE_Unbounded_Queue_Iterator<ACE_Thread_Descriptor*>
#  pragma instantiate ACE_Free_List<ACE_Thread_Descriptor>
#  pragma instantiate ACE_Locked_Free_List<ACE_Thread_Descriptor, ACE_DEFAULT_THREAD_MANAGER_LOCK>
#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */