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
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
| /*
* threadCmd.c --
*
* This file implements the Tcl thread commands that allow script
* level access to threading. It will not load into a core that was
* not compiled for thread support.
*
* See http://www.tcl.tk/doc/howto/thread_model.html
*
* Some of this code is based on work done by Richard Hipp on behalf of
* Conservation Through Innovation, Limited, with their permission.
*
* Copyright (c) 1998 by Sun Microsystems, Inc.
* Copyright (c) 1999,2000 by Scriptics Corporation.
* Copyright (c) 2002 by Zoran Vasiljevic.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
* ----------------------------------------------------------------------------
*/
#include "tclThreadInt.h"
/*
* Provide package version in build contexts which do not provide
* -DPACKAGE_VERSION, like building a shell with the Thread object
* files built as part of that shell. Example: basekits.
*/
#ifndef PACKAGE_VERSION
#define PACKAGE_VERSION "2.9a1"
#endif
/*
* Check if this is Tcl 8.5 or higher. In that case, we will have the TIP
* #143 APIs (i.e. interpreter resource limiting) available.
*/
#ifndef TCL_TIP143
# if TCL_MINIMUM_VERSION(8,5)
# define TCL_TIP143
# endif
#endif
/*
* If TIP #143 support is enabled and we are compiling against a pre-Tcl 8.5
* core, hard-wire the necessary APIs using the "well-known" offsets into the
* stubs table.
*/
#define haveInterpLimit (threadTclVersion>=85)
#if defined(TCL_TIP143) && !TCL_MINIMUM_VERSION(8,5)
# if defined(USE_TCL_STUBS)
# define Tcl_LimitExceeded ((int (*)(Tcl_Interp *)) \
((&(tclStubsPtr->tcl_PkgProvideEx))[524]))
# else
# error "Supporting TIP #143 requires USE_TCL_STUBS before Tcl 8.5"
# endif
#endif
/*
* Check if this is Tcl 8.6 or higher. In that case, we will have the TIP
* #285 APIs (i.e. asynchronous script cancellation) available.
*/
#define haveInterpCancel (threadTclVersion>=86)
#ifndef TCL_TIP285
# if TCL_MINIMUM_VERSION(8,6)
# define TCL_TIP285
# endif
#endif
/*
* If TIP #285 support is enabled and we are compiling against a pre-Tcl 8.6
* core, hard-wire the necessary APIs using the "well-known" offsets into the
* stubs table.
*/
#if defined(TCL_TIP285) && !TCL_MINIMUM_VERSION(8,6)
# if defined(USE_TCL_STUBS)
# define TCL_CANCEL_UNWIND 0x100000
# define Tcl_CancelEval ((int (*)(Tcl_Interp *, Tcl_Obj *, ClientData, int)) \
((&(tclStubsPtr->tcl_PkgProvideEx))[580]))
# define Tcl_Canceled ((int (*)(Tcl_Interp *, int)) \
((&(tclStubsPtr->tcl_PkgProvideEx))[581]))
# else
# error "Supporting TIP #285 requires USE_TCL_STUBS before Tcl 8.6"
# endif
#endif
/*
* Access to the list of threads and to the thread send results
* (defined below) is guarded by this mutex.
*/
TCL_DECLARE_MUTEX(threadMutex)
/*
* Each thread has an single instance of the following structure. There
* is one instance of this structure per thread even if that thread contains
* multiple interpreters. The interpreter identified by this structure is
* the main interpreter for the thread. The main interpreter is the one that
* will process any messages received by a thread. Any interpreter can send
* messages but only the main interpreter can receive them, unless you're
* not doing asynchronous script backfiring. In such cases the caller might
* signal the thread to which interpreter the result should be delivered.
*/
typedef struct ThreadSpecificData {
Tcl_ThreadId threadId; /* The real ID of this thread */
Tcl_Interp *interp; /* Main interp for this thread */
Tcl_Condition doOneEvent; /* Signalled just before running
an event from the event loop */
int flags; /* One of the ThreadFlags below */
int refCount; /* Used for thread reservation */
int eventsPending; /* # of unprocessed events */
int maxEventsCount; /* Maximum # of pending events */
struct ThreadEventResult *result;
struct ThreadSpecificData *nextPtr;
struct ThreadSpecificData *prevPtr;
} ThreadSpecificData;
static Tcl_ThreadDataKey dataKey;
#define THREAD_FLAGS_NONE 0 /* None */
#define THREAD_FLAGS_STOPPED 1 /* Thread is being stopped */
#define THREAD_FLAGS_INERROR 2 /* Thread is in error */
#define THREAD_FLAGS_UNWINDONERROR 4 /* Thread unwinds on script error */
#define THREAD_RESERVE 1 /* Reserves the thread */
#define THREAD_RELEASE 2 /* Releases the thread */
/*
* Length of storage for building the Tcl handle for the thread.
*/
#define THREAD_HNDLPREFIX "tid"
#define THREAD_HNDLMAXLEN 32
/*
* This list is used to list all threads that have interpreters.
*/
static struct ThreadSpecificData *threadList = NULL;
/*
* Used to represent the empty result.
*/
static char *threadEmptyResult = (char *)"";
int threadTclVersion = 0;
/*
* An instance of the following structure contains all information that is
* passed into a new thread when the thread is created using either the
* "thread create" Tcl command or the ThreadCreate() C function.
*/
typedef struct ThreadCtrl {
char *script; /* Script to execute */
int flags; /* Initial value of the "flags"
* field in ThreadSpecificData */
Tcl_Condition condWait; /* Condition variable used to
* sync parent and child threads */
ClientData cd; /* Opaque ptr to pass to thread */
} ThreadCtrl;
/*
* Structure holding result of the command executed in target thread.
*/
typedef struct ThreadEventResult {
Tcl_Condition done; /* Set when the script completes */
int code; /* Return value of the function */
char *result; /* Result from the function */
char *errorInfo; /* Copy of errorInfo variable */
char *errorCode; /* Copy of errorCode variable */
Tcl_ThreadId srcThreadId; /* Id of sender, if it dies */
Tcl_ThreadId dstThreadId; /* Id of target, if it dies */
struct ThreadEvent *eventPtr; /* Back pointer */
struct ThreadEventResult *nextPtr; /* List for cleanup */
struct ThreadEventResult *prevPtr;
} ThreadEventResult;
/*
* This list links all active ThreadEventResult structures. This way
* an exiting thread can inform all threads waiting on jobs posted to
* his event queue that it is dying, so they might stop waiting.
*/
static ThreadEventResult *resultList;
/*
* This is the event used to send commands to other threads.
*/
typedef struct ThreadEvent {
Tcl_Event event; /* Must be first */
struct ThreadSendData *sendData; /* See below */
struct ThreadClbkData *clbkData; /* See below */
struct ThreadEventResult *resultPtr; /* To communicate the result back.
* NULL if we don't care about it */
} ThreadEvent;
typedef int (ThreadSendProc) (Tcl_Interp*, ClientData);
typedef void (ThreadSendFree) (ClientData);
static ThreadSendProc ThreadSendEval; /* Does a regular Tcl_Eval */
static ThreadSendProc ThreadClbkSetVar; /* Sets the named variable */
/*
* These structures are used to communicate commands between source and target
* threads. The ThreadSendData is used for source->target command passing,
* while the ThreadClbkData is used for doing asynchronous callbacks.
*
* Important: structures below must have first three elements identical!
*/
typedef struct ThreadSendData {
ThreadSendProc *execProc; /* Func to exec in remote thread */
ClientData clientData; /* Ptr to pass to send function */
ThreadSendFree *freeProc; /* Function to free client data */
/* ---- */
Tcl_Interp *interp; /* Interp to run the command */
} ThreadSendData;
typedef struct ThreadClbkData {
ThreadSendProc *execProc; /* The callback function */
ClientData clientData; /* Ptr to pass to clbk function */
ThreadSendFree *freeProc; /* Function to free client data */
/* ---- */
Tcl_Interp *interp; /* Interp to run the command */
Tcl_ThreadId threadId; /* Thread where to post callback */
ThreadEventResult result; /* Returns result asynchronously */
} ThreadClbkData;
/*
* Event used to transfer a channel between threads.
*/
typedef struct TransferEvent {
Tcl_Event event; /* Must be first */
Tcl_Channel chan; /* The channel to transfer */
struct TransferResult *resultPtr; /* To communicate the result */
} TransferEvent;
typedef struct TransferResult {
Tcl_Condition done; /* Set when transfer is done */
int resultCode; /* Set to TCL_OK or TCL_ERROR when
the transfer is done. Def = -1 */
char *resultMsg; /* Initialized to NULL. Set to a
allocated string by the target
thread in case of an error */
Tcl_ThreadId srcThreadId; /* Id of src thread, if it dies */
Tcl_ThreadId dstThreadId; /* Id of tgt thread, if it dies */
struct TransferEvent *eventPtr; /* Back pointer */
struct TransferResult *nextPtr; /* Next in the linked list */
struct TransferResult *prevPtr; /* Previous in the linked list */
} TransferResult;
static TransferResult *transferList;
/*
* This is for simple error handling when a thread script exits badly.
*/
static Tcl_ThreadId errorThreadId; /* Id of thread to post error message */
static char *errorProcString; /* Tcl script to run when reporting error */
/*
* Definition of flags for ThreadSend.
*/
#define THREAD_SEND_WAIT (1<<1)
#define THREAD_SEND_HEAD (1<<2)
#define THREAD_SEND_CLBK (1<<3)
#ifdef BUILD_thread
# undef TCL_STORAGE_CLASS
# define TCL_STORAGE_CLASS DLLEXPORT
#endif
/*
* Miscellaneous functions used within this file
*/
static Tcl_EventDeleteProc ThreadDeleteEvent;
static Tcl_ThreadCreateType
NewThread(ClientData clientData);
static ThreadSpecificData*
ThreadExistsInner(Tcl_ThreadId id);
static int
ThreadInit(Tcl_Interp *interp);
static int
ThreadCreate(Tcl_Interp *interp,
const char *script,
int stacksize,
int flags,
int preserve);
static int
ThreadSend(Tcl_Interp *interp,
Tcl_ThreadId id,
ThreadSendData *sendPtr,
ThreadClbkData *clbkPtr,
int flags);
static void
ThreadSetResult(Tcl_Interp *interp,
int code,
ThreadEventResult *resultPtr);
static int
ThreadGetOption(Tcl_Interp *interp,
Tcl_ThreadId id,
char *option,
Tcl_DString *ds);
static int
ThreadSetOption(Tcl_Interp *interp,
Tcl_ThreadId id,
char *option,
char *value);
static int
ThreadReserve(Tcl_Interp *interp,
Tcl_ThreadId id,
int operation,
int wait);
static int
ThreadEventProc(Tcl_Event *evPtr,
int mask);
static int
ThreadWait(Tcl_Interp *interp);
static int
ThreadExists(Tcl_ThreadId id);
static int
ThreadList(Tcl_Interp *interp,
Tcl_ThreadId **thrIdArray);
static void
ThreadErrorProc(Tcl_Interp *interp);
static void
ThreadFreeProc(ClientData clientData);
static void
ThreadIdleProc(ClientData clientData);
static void
ThreadExitProc(ClientData clientData);
static void
ThreadFreeError(ClientData clientData);
static void
ListRemove(ThreadSpecificData *tsdPtr);
static void
ListRemoveInner(ThreadSpecificData *tsdPtr);
static void
ListUpdate(ThreadSpecificData *tsdPtr);
static void
ListUpdateInner(ThreadSpecificData *tsdPtr);
static int
ThreadJoin(Tcl_Interp *interp,
Tcl_ThreadId id);
static int
ThreadTransfer(Tcl_Interp *interp,
Tcl_ThreadId id,
Tcl_Channel chan);
static int
ThreadDetach(Tcl_Interp *interp,
Tcl_Channel chan);
static int
ThreadAttach(Tcl_Interp *interp,
char *chanName);
static int
TransferEventProc(Tcl_Event *evPtr,
int mask);
static void
ThreadGetHandle(Tcl_ThreadId,
char *handlePtr);
static int
ThreadGetId(Tcl_Interp *interp,
Tcl_Obj *handleObj,
Tcl_ThreadId *thrIdPtr);
static void
ErrorNoSuchThread(Tcl_Interp *interp,
Tcl_ThreadId thrId);
static void
ThreadCutChannel(Tcl_Interp *interp,
Tcl_Channel channel);
#ifdef TCL_TIP285
static int
ThreadCancel(Tcl_Interp *interp,
Tcl_ThreadId thrId,
const char *result,
int flags);
#endif
/*
* Functions implementing Tcl commands
*/
static Tcl_ObjCmdProc ThreadCreateObjCmd;
static Tcl_ObjCmdProc ThreadReserveObjCmd;
static Tcl_ObjCmdProc ThreadReleaseObjCmd;
static Tcl_ObjCmdProc ThreadSendObjCmd;
static Tcl_ObjCmdProc ThreadBroadcastObjCmd;
static Tcl_ObjCmdProc ThreadUnwindObjCmd;
static Tcl_ObjCmdProc ThreadExitObjCmd;
static Tcl_ObjCmdProc ThreadIdObjCmd;
static Tcl_ObjCmdProc ThreadNamesObjCmd;
static Tcl_ObjCmdProc ThreadWaitObjCmd;
static Tcl_ObjCmdProc ThreadExistsObjCmd;
static Tcl_ObjCmdProc ThreadConfigureObjCmd;
static Tcl_ObjCmdProc ThreadErrorProcObjCmd;
static Tcl_ObjCmdProc ThreadJoinObjCmd;
static Tcl_ObjCmdProc ThreadTransferObjCmd;
static Tcl_ObjCmdProc ThreadDetachObjCmd;
static Tcl_ObjCmdProc ThreadAttachObjCmd;
#ifdef TCL_TIP285
static Tcl_ObjCmdProc ThreadCancelObjCmd;
#endif
static int
ThreadInit(interp)
Tcl_Interp *interp; /* The current Tcl interpreter */
{
if (Tcl_InitStubs(interp, "8.4", 0) == NULL) {
if ((sizeof(size_t) != sizeof(int))
#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION >= 7 && defined(TCL_NO_DEPRECATED)
/* As long as Tcl 8.7 is not final, this allows the Thread extension */
/* to be loadable on Tcl 9.0, provided it is compiled against Tcl 8.7+ headers */
|| !(Tcl_InitStubs)(interp, "8.4-",
(TCL_MAJOR_VERSION<<8)|(TCL_MINOR_VERSION<<16), TCL_STUB_MAGIC)
#endif
) {
return TCL_ERROR;
}
Tcl_ResetResult(interp);
}
if (!threadTclVersion) {
/*
* Check whether we are running threaded Tcl.
* Get the current core version to decide whether to use
* some lately introduced core features or to back-off.
*/
int major, minor;
Tcl_MutexLock(&threadMutex);
if (threadMutex == NULL){
/* If threadMutex==NULL here, it means that Tcl_MutexLock() is
* a dummy function, which is the case in unthreaded Tcl */
const char *msg = "Tcl core wasn't compiled for threading";
Tcl_SetObjResult(interp, Tcl_NewStringObj(msg, -1));
return TCL_ERROR;
}
Tcl_GetVersion(&major, &minor, NULL, NULL);
threadTclVersion = 10 * major + minor;
Tcl_MutexUnlock(&threadMutex);
}
TCL_CMD(interp, THREAD_CMD_PREFIX"create", ThreadCreateObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"send", ThreadSendObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"broadcast", ThreadBroadcastObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"exit", ThreadExitObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"unwind", ThreadUnwindObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"id", ThreadIdObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"names", ThreadNamesObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"exists", ThreadExistsObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"wait", ThreadWaitObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"configure", ThreadConfigureObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"errorproc", ThreadErrorProcObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"preserve", ThreadReserveObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"release", ThreadReleaseObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"join", ThreadJoinObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"transfer", ThreadTransferObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"detach", ThreadDetachObjCmd);
TCL_CMD(interp, THREAD_CMD_PREFIX"attach", ThreadAttachObjCmd);
#ifdef TCL_TIP285
TCL_CMD(interp, THREAD_CMD_PREFIX"cancel", ThreadCancelObjCmd);
#endif
/*
* Add shared variable commands
*/
Sv_Init(interp);
/*
* Add commands to access thread
* synchronization primitives.
*/
Sp_Init(interp);
/*
* Add threadpool commands.
*/
Tpool_Init(interp);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Thread_Init --
*
* Initialize the thread commands.
*
* Results:
* TCL_OK if the package was properly initialized.
*
* Side effects:
* Adds package commands to the current interp.
*
*----------------------------------------------------------------------
*/
DLLEXPORT int
Thread_Init(interp)
Tcl_Interp *interp; /* The current Tcl interpreter */
{
int status = ThreadInit(interp);
if (status != TCL_OK) {
return status;
}
return Tcl_PkgProvideEx(interp, "Thread", PACKAGE_VERSION, NULL);
}
/*
*----------------------------------------------------------------------
*
* Init --
*
* Make sure internal list of threads references the current thread.
*
* Results:
* None
*
* Side effects:
* The list of threads is initialized to include the current thread.
*
*----------------------------------------------------------------------
*/
static void
Init(interp)
Tcl_Interp *interp; /* Current interpreter. */
{
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
if (tsdPtr->interp == (Tcl_Interp*)NULL) {
memset(tsdPtr, 0, sizeof(ThreadSpecificData));
tsdPtr->interp = interp;
ListUpdate(tsdPtr);
Tcl_CreateThreadExitHandler(ThreadExitProc,
(ClientData)threadEmptyResult);
}
}
/*
*----------------------------------------------------------------------
*
* ThreadCreateObjCmd --
*
* This procedure is invoked to process the "thread::create" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadCreateObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
int argc, rsrv = 0;
const char *arg, *script;
int flags = TCL_THREAD_NOFLAGS;
Init(interp);
/*
* Syntax: thread::create ?-joinable? ?-preserved? ?script?
*/
script = THREAD_CMD_PREFIX"wait";
for (argc = 1; argc < objc; argc++) {
arg = Tcl_GetString(objv[argc]);
if (OPT_CMP(arg, "--")) {
argc++;
if ((argc + 1) == objc) {
script = Tcl_GetString(objv[argc]);
} else {
goto usage;
}
break;
} else if (OPT_CMP(arg, "-joinable")) {
flags |= TCL_THREAD_JOINABLE;
} else if (OPT_CMP(arg, "-preserved")) {
rsrv = 1;
} else if ((argc + 1) == objc) {
script = Tcl_GetString(objv[argc]);
} else {
goto usage;
}
}
return ThreadCreate(interp, script, TCL_THREAD_STACK_DEFAULT, flags, rsrv);
usage:
Tcl_WrongNumArgs(interp, 1, objv, "?-joinable? ?script?");
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* ThreadReserveObjCmd --
*
* This procedure is invoked to process the "thread::preserve" and
* "thread::release" Tcl commands, depending on the flag passed by
* the ClientData argument. See the user documentation for details
* on what those command do.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadReserveObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Tcl_ThreadId thrId = (Tcl_ThreadId)0;
Init(interp);
if (objc > 2) {
Tcl_WrongNumArgs(interp, 1, objv, "?threadId?");
return TCL_ERROR;
}
if (objc == 2) {
if (ThreadGetId(interp, objv[1], &thrId) != TCL_OK) {
return TCL_ERROR;
}
}
return ThreadReserve(interp, thrId, THREAD_RESERVE, 0);
}
/*
*----------------------------------------------------------------------
*
* ThreadReleaseObjCmd --
*
* This procedure is invoked to process the "thread::release" Tcl
* command. See the user documentation for details on what this
* command does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadReleaseObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
int wait = 0;
Tcl_ThreadId thrId = (Tcl_ThreadId)0;
Init(interp);
if (objc > 3) {
Tcl_WrongNumArgs(interp, 1, objv, "?-wait? ?threadId?");
return TCL_ERROR;
}
if (objc > 1) {
if (OPT_CMP(Tcl_GetString(objv[1]), "-wait")) {
wait = 1;
if (objc > 2) {
if (ThreadGetId(interp, objv[2], &thrId) != TCL_OK) {
return TCL_ERROR;
}
}
} else if (ThreadGetId(interp, objv[1], &thrId) != TCL_OK) {
return TCL_ERROR;
}
}
return ThreadReserve(interp, thrId, THREAD_RELEASE, wait);
}
/*
*----------------------------------------------------------------------
*
* ThreadUnwindObjCmd --
*
* This procedure is invoked to process the "thread::unwind" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadUnwindObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Init(interp);
if (objc > 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
return ThreadReserve(interp, 0, THREAD_RELEASE, 0);
}
/*
*----------------------------------------------------------------------
*
* ThreadExitObjCmd --
*
* This procedure is invoked to process the "thread::exit" Tcl
* command. This causes an unconditional close of the thread
* and is GUARANTEED to cause memory leaks. Use this with caution.
*
* Results:
* Doesn't actually return.
*
* Side effects:
* Lots. improper clean up of resources.
*
*----------------------------------------------------------------------
*/
static int
ThreadExitObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
int status = 666;
Init(interp);
if (objc > 2) {
Tcl_WrongNumArgs(interp, 1, objv, "?status?");
return TCL_ERROR;
}
if (objc == 2) {
if (Tcl_GetIntFromObj(interp, objv[1], &status) != TCL_OK) {
return TCL_ERROR;
}
}
ListRemove(NULL);
Tcl_ExitThread(status);
return TCL_OK; /* NOT REACHED */
}
/*
*----------------------------------------------------------------------
*
* ThreadIdObjCmd --
*
* This procedure is invoked to process the "thread::id" Tcl command.
* This returns the ID of the current thread.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ThreadIdObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
char thrHandle[THREAD_HNDLMAXLEN];
Init(interp);
if (objc > 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
ThreadGetHandle(Tcl_GetCurrentThread(), thrHandle);
Tcl_SetObjResult(interp, Tcl_NewStringObj(thrHandle, -1));
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadNamesObjCmd --
*
* This procedure is invoked to process the "thread::names" Tcl
* command. This returns a list of all known thread IDs.
* These are only threads created via this module (e.g., not
* driver threads or the notifier).
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ThreadNamesObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
int ii, length;
char *result, thrHandle[THREAD_HNDLMAXLEN];
Tcl_ThreadId *thrIdArray;
Tcl_DString threadNames;
Init(interp);
if (objc > 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
length = ThreadList(interp, &thrIdArray);
if (length == 0) {
return TCL_OK;
}
Tcl_DStringInit(&threadNames);
for (ii = 0; ii < length; ii++) {
ThreadGetHandle(thrIdArray[ii], thrHandle);
Tcl_DStringAppendElement(&threadNames, thrHandle);
}
length = Tcl_DStringLength(&threadNames);
result = Tcl_DStringValue(&threadNames);
Tcl_SetObjResult(interp, Tcl_NewStringObj(result, length));
Tcl_DStringFree(&threadNames);
ckfree((char*)thrIdArray);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadSendObjCmd --
*
* This procedure is invoked to process the "thread::send" Tcl
* command. This sends a script to another thread for execution.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
threadSendFree(ClientData ptr)
{
ckfree((char *)ptr);
}
static int
ThreadSendObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
size_t len, vlen = 0;
int ret, ii = 0, flags = 0;
Tcl_ThreadId thrId;
const char *script, *arg;
Tcl_Obj *var = NULL;
ThreadClbkData *clbkPtr = NULL;
ThreadSendData *sendPtr = NULL;
Init(interp);
/*
* Syntax: thread::send ?-async? ?-head? threadId script ?varName?
*/
if (objc < 3 || objc > 6) {
goto usage;
}
flags = THREAD_SEND_WAIT;
for (ii = 1; ii < objc; ii++) {
arg = Tcl_GetString(objv[ii]);
if (OPT_CMP(arg, "-async")) {
flags &= ~THREAD_SEND_WAIT;
} else if (OPT_CMP(arg, "-head")) {
flags |= THREAD_SEND_HEAD;
} else {
break;
}
}
if (ii >= objc) {
goto usage;
}
if (ThreadGetId(interp, objv[ii], &thrId) != TCL_OK) {
return TCL_ERROR;
}
if (++ii >= objc) {
goto usage;
}
script = Tcl_GetString(objv[ii]);
len = objv[ii]->length;
if (++ii < objc) {
var = objv[ii];
vlen = objv[ii]->length;
}
if (var && (flags & THREAD_SEND_WAIT) == 0) {
if (thrId == Tcl_GetCurrentThread()) {
/*
* FIXME: Do something for callbacks to self
*/
Tcl_SetObjResult(interp, Tcl_NewStringObj("can't notify self", -1));
return TCL_ERROR;
}
/*
* Prepare record for the callback. This is asynchronously
* posted back to us when the target thread finishes processing.
* We should do a vwait on the "var" to get notified.
*/
clbkPtr = (ThreadClbkData*)ckalloc(sizeof(ThreadClbkData));
clbkPtr->execProc = ThreadClbkSetVar;
clbkPtr->freeProc = threadSendFree;
clbkPtr->interp = interp;
clbkPtr->threadId = Tcl_GetCurrentThread();
clbkPtr->clientData = (ClientData)strcpy(ckalloc(1+vlen), Tcl_GetString(var));
}
/*
* Prepare job record for the target thread
*/
sendPtr = (ThreadSendData*)ckalloc(sizeof(ThreadSendData));
sendPtr->interp = NULL; /* Signal to use thread main interp */
sendPtr->execProc = ThreadSendEval;
sendPtr->freeProc = threadSendFree;
sendPtr->clientData = (ClientData)strcpy(ckalloc(1+len), script);
ret = ThreadSend(interp, thrId, sendPtr, clbkPtr, flags);
if (var && (flags & THREAD_SEND_WAIT)) {
/*
* Leave job's result in passed variable
* and return the code, like "catch" does.
*/
Tcl_Obj *resultObj = Tcl_GetObjResult(interp);
if (!Tcl_ObjSetVar2(interp, var, NULL, resultObj, TCL_LEAVE_ERR_MSG)) {
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tcl_NewIntObj(ret));
return TCL_OK;
}
return ret;
usage:
Tcl_WrongNumArgs(interp,1,objv,"?-async? ?-head? id script ?varName?");
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* ThreadBroadcastObjCmd --
*
* This procedure is invoked to process the "thread::broadcast" Tcl
* command. This asynchronously sends a script to all known threads.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Script is sent to all known threads except the caller thread.
*
*----------------------------------------------------------------------
*/
static int
ThreadBroadcastObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
int ii, nthreads;
size_t len;
const char *script;
Tcl_ThreadId *thrIdArray;
ThreadSendData *sendPtr, job;
Init(interp);
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "script");
return TCL_ERROR;
}
script = Tcl_GetString(objv[1]);
len = objv[1]->length;
/*
* Get the list of known threads. Note that this one may
* actually change (thread may exit or otherwise cease to
* exist) while we circle in the loop below. We really do
* not care about that here since we don't return any
* script results to the caller.
*/
nthreads = ThreadList(interp, &thrIdArray);
if (nthreads == 0) {
return TCL_OK;
}
/*
* Prepare the structure with the job description
* to be sent asynchronously to each known thread.
*/
job.interp = NULL; /* Signal to use thread's main interp */
job.execProc = ThreadSendEval;
job.freeProc = threadSendFree;
job.clientData = NULL;
/*
* Now, circle this list and send each thread the script.
* This is sent asynchronously, since we do not care what
* are they going to do with it. Also, the event is queued
* to the head of the event queue (as out-of-band message).
*/
for (ii = 0; ii < nthreads; ii++) {
if (thrIdArray[ii] == Tcl_GetCurrentThread()) {
continue; /* Do not broadcast self */
}
sendPtr = (ThreadSendData*)ckalloc(sizeof(ThreadSendData));
*sendPtr = job;
sendPtr->clientData = (ClientData)strcpy(ckalloc(1+len), script);
ThreadSend(interp, thrIdArray[ii], sendPtr, NULL, THREAD_SEND_HEAD);
}
ckfree((char*)thrIdArray);
Tcl_ResetResult(interp);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadWaitObjCmd --
*
* This procedure is invoked to process the "thread::wait" Tcl
* command. This enters the event loop.
*
* Results:
* Standard Tcl result.
*
* Side effects:
* Enters the event loop.
*
*----------------------------------------------------------------------
*/
static int
ThreadWaitObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Init(interp);
if (objc > 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
return ThreadWait(interp);
}
/*
*----------------------------------------------------------------------
*
* ThreadErrorProcObjCmd --
*
* This procedure is invoked to process the "thread::errorproc"
* command. This registers a procedure to handle thread errors.
* Empty string as the name of the procedure will reset the
* default behaviour, which is writing to standard error channel.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Registers an errorproc.
*
*----------------------------------------------------------------------
*/
static int
ThreadErrorProcObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
size_t len;
char *proc;
Init(interp);
if (objc > 2) {
Tcl_WrongNumArgs(interp, 1, objv, "?proc?");
return TCL_ERROR;
}
Tcl_MutexLock(&threadMutex);
if (objc == 1) {
if (errorProcString) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(errorProcString, -1));
}
} else {
if (errorProcString) {
ckfree(errorProcString);
}
proc = Tcl_GetString(objv[1]);
len = objv[1]->length;
if (len == 0) {
errorThreadId = NULL;
errorProcString = NULL;
} else {
errorThreadId = Tcl_GetCurrentThread();
errorProcString = ckalloc(1+strlen(proc));
strcpy(errorProcString, proc);
Tcl_DeleteThreadExitHandler(ThreadFreeError, NULL);
Tcl_CreateThreadExitHandler(ThreadFreeError, NULL);
}
}
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
static void
ThreadFreeError(clientData)
ClientData clientData;
{
Tcl_MutexLock(&threadMutex);
if (errorThreadId != Tcl_GetCurrentThread()) {
Tcl_MutexUnlock(&threadMutex);
return;
}
ckfree(errorProcString);
errorThreadId = NULL;
errorProcString = NULL;
Tcl_MutexUnlock(&threadMutex);
}
/*
*----------------------------------------------------------------------
*
* ThreadJoinObjCmd --
*
* This procedure is invoked to process the "thread::join" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadJoinObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Tcl_ThreadId thrId;
Init(interp);
/*
* Syntax of 'join': id
*/
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "id");
return TCL_ERROR;
}
if (ThreadGetId(interp, objv[1], &thrId) != TCL_OK) {
return TCL_ERROR;
}
return ThreadJoin(interp, thrId);
}
/*
*----------------------------------------------------------------------
*
* ThreadTransferObjCmd --
*
* This procedure is invoked to process the "thread::transfer" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadTransferObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Tcl_ThreadId thrId;
Tcl_Channel chan;
Init(interp);
/*
* Syntax of 'transfer': id channel
*/
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "id channel");
return TCL_ERROR;
}
if (ThreadGetId(interp, objv[1], &thrId) != TCL_OK) {
return TCL_ERROR;
}
chan = Tcl_GetChannel(interp, Tcl_GetString(objv[2]), NULL);
if (chan == (Tcl_Channel)NULL) {
return TCL_ERROR;
}
return ThreadTransfer(interp, thrId, Tcl_GetTopChannel(chan));
}
/*
*----------------------------------------------------------------------
*
* ThreadDetachObjCmd --
*
* This procedure is invoked to process the "thread::detach" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadDetachObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Tcl_Channel chan;
Init(interp);
/*
* Syntax: thread::detach channel
*/
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "channel");
return TCL_ERROR;
}
chan = Tcl_GetChannel(interp, Tcl_GetString(objv[1]), NULL);
if (chan == (Tcl_Channel)NULL) {
return TCL_ERROR;
}
return ThreadDetach(interp, Tcl_GetTopChannel(chan));
}
/*
*----------------------------------------------------------------------
*
* ThreadAttachObjCmd --
*
* This procedure is invoked to process the "thread::attach" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadAttachObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
char *chanName;
Init(interp);
/*
* Syntax: thread::attach channel
*/
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "channel");
return TCL_ERROR;
}
chanName = Tcl_GetString(objv[1]);
if (Tcl_IsChannelExisting(chanName)) {
return TCL_OK;
}
return ThreadAttach(interp, chanName);
}
/*
*----------------------------------------------------------------------
*
* ThreadExistsObjCmd --
*
* This procedure is invoked to process the "thread::exists" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadExistsObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Tcl_ThreadId thrId;
Init(interp);
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "id");
return TCL_ERROR;
}
if (ThreadGetId(interp, objv[1], &thrId) != TCL_OK) {
return TCL_ERROR;
}
Tcl_SetIntObj(Tcl_GetObjResult(interp), ThreadExists(thrId)!=0);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadConfigureObjCmd --
*
* This procedure is invoked to process the Tcl "thread::configure"
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*----------------------------------------------------------------------
*/
static int
ThreadConfigureObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
char *option, *value;
Tcl_ThreadId thrId; /* Id of the thread to configure */
int i; /* Iterate over arg-value pairs. */
Tcl_DString ds; /* DString to hold result of
* calling GetThreadOption. */
if (objc < 2 || (objc % 2 == 1 && objc != 3)) {
Tcl_WrongNumArgs(interp, 1, objv, "threadlId ?optionName? "
"?value? ?optionName value?...");
return TCL_ERROR;
}
Init(interp);
if (ThreadGetId(interp, objv[1], &thrId) != TCL_OK) {
return TCL_ERROR;
}
if (objc == 2) {
Tcl_DStringInit(&ds);
if (ThreadGetOption(interp, thrId, NULL, &ds) != TCL_OK) {
Tcl_DStringFree(&ds);
return TCL_ERROR;
}
Tcl_DStringResult(interp, &ds);
return TCL_OK;
}
if (objc == 3) {
Tcl_DStringInit(&ds);
option = Tcl_GetString(objv[2]);
if (ThreadGetOption(interp, thrId, option, &ds) != TCL_OK) {
Tcl_DStringFree(&ds);
return TCL_ERROR;
}
Tcl_DStringResult(interp, &ds);
return TCL_OK;
}
for (i = 3; i < objc; i += 2) {
option = Tcl_GetString(objv[i-1]);
value = Tcl_GetString(objv[i]);
if (ThreadSetOption(interp, thrId, option, value) != TCL_OK) {
return TCL_ERROR;
}
}
return TCL_OK;
}
#ifdef TCL_TIP285
/*
*----------------------------------------------------------------------
*
* ThreadCancelObjCmd --
*
* This procedure is invoked to process the "thread::cancel" Tcl
* command. See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
static int
ThreadCancelObjCmd(dummy, interp, objc, objv)
ClientData dummy; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *const objv[]; /* Argument objects. */
{
Tcl_ThreadId thrId;
int ii, flags;
const char *result;
if ((objc < 2) || (objc > 4)) {
Tcl_WrongNumArgs(interp, 1, objv, "?-unwind? id ?result?");
return TCL_ERROR;
}
flags = 0;
ii = 1;
if ((objc == 3) || (objc == 4)) {
if (OPT_CMP(Tcl_GetString(objv[ii]), "-unwind")) {
flags |= TCL_CANCEL_UNWIND;
ii++;
}
}
if (ThreadGetId(interp, objv[ii], &thrId) != TCL_OK) {
return TCL_ERROR;
}
ii++;
if (ii < objc) {
result = Tcl_GetString(objv[ii]);
} else {
result = NULL;
}
return ThreadCancel(interp, thrId, result, flags);
}
#endif
/*
*----------------------------------------------------------------------
*
* ThreadSendEval --
*
* Evaluates Tcl script passed from source to target thread.
*
* Results:
* A standard Tcl result.
*
* Side effects:
*
*----------------------------------------------------------------------
*/
static int
ThreadSendEval(interp, clientData)
Tcl_Interp *interp;
ClientData clientData;
{
ThreadSendData *sendPtr = (ThreadSendData*)clientData;
char *script = (char*)sendPtr->clientData;
return Tcl_EvalEx(interp, script, -1, TCL_EVAL_GLOBAL);
}
/*
*----------------------------------------------------------------------
*
* ThreadClbkSetVar --
*
* Sets the Tcl variable in the source thread, as the result
* of the asynchronous callback.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* New Tcl variable may be created
*
*----------------------------------------------------------------------
*/
static int
ThreadClbkSetVar(interp, clientData)
Tcl_Interp *interp;
ClientData clientData;
{
ThreadClbkData *clbkPtr = (ThreadClbkData*)clientData;
const char *var = (const char *)clbkPtr->clientData;
Tcl_Obj *valObj;
ThreadEventResult *resultPtr = &clbkPtr->result;
int rc = TCL_OK;
/*
* Get the result of the posted command.
* We will use it to fill-in the result variable.
*/
valObj = Tcl_NewStringObj(resultPtr->result, -1);
Tcl_IncrRefCount(valObj);
if (resultPtr->result != threadEmptyResult) {
ckfree(resultPtr->result);
}
/*
* Set the result variable
*/
if (Tcl_SetVar2Ex(interp, var, NULL, valObj,
TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG) == NULL) {
rc = TCL_ERROR;
goto cleanup;
}
/*
* In case of error, trigger the bgerror mechansim
*/
if (resultPtr->code == TCL_ERROR) {
if (resultPtr->errorCode) {
var = "errorCode";
Tcl_SetVar2Ex(interp, var, NULL, Tcl_NewStringObj(resultPtr->errorCode, -1), TCL_GLOBAL_ONLY);
ckfree((char*)resultPtr->errorCode);
}
if (resultPtr->errorInfo) {
var = "errorInfo";
Tcl_SetVar2Ex(interp, var, NULL, Tcl_NewStringObj(resultPtr->errorInfo, -1), TCL_GLOBAL_ONLY);
ckfree((char*)resultPtr->errorInfo);
}
Tcl_SetObjResult(interp, valObj);
Tcl_BackgroundError(interp);
}
cleanup:
Tcl_DecrRefCount(valObj);
return rc;
}
/*
*----------------------------------------------------------------------
*
* ThreadCreate --
*
* This procedure is invoked to create a thread containing an
* interp to run a script. This returns after the thread has
* started executing.
*
* Results:
* A standard Tcl result, which is the thread ID.
*
* Side effects:
* Create a thread.
*
*----------------------------------------------------------------------
*/
static int
ThreadCreate(interp, script, stacksize, flags, preserve)
Tcl_Interp *interp; /* Current interpreter. */
const char *script; /* Script to evaluate */
int stacksize; /* Zero for default size */
int flags; /* Zero for no flags */
int preserve; /* If true, reserve the thread */
{
char thrHandle[THREAD_HNDLMAXLEN];
ThreadCtrl ctrl;
Tcl_ThreadId thrId;
ctrl.cd = Tcl_GetAssocData(interp, "thread:nsd", NULL);
ctrl.script = (char *)script;
ctrl.condWait = NULL;
ctrl.flags = 0;
Tcl_MutexLock(&threadMutex);
if (Tcl_CreateThread(&thrId, NewThread, (ClientData)&ctrl,
stacksize, flags) != TCL_OK) {
Tcl_MutexUnlock(&threadMutex);
Tcl_SetObjResult(interp, Tcl_NewStringObj("can't create a new thread", -1));
return TCL_ERROR;
}
/*
* Wait for the thread to start because it is using
* the ThreadCtrl argument which is on our stack.
*/
while (ctrl.script != NULL) {
Tcl_ConditionWait(&ctrl.condWait, &threadMutex, NULL);
}
if (preserve) {
ThreadSpecificData *tsdPtr = ThreadExistsInner(thrId);
if (tsdPtr == (ThreadSpecificData*)NULL) {
Tcl_MutexUnlock(&threadMutex);
Tcl_ConditionFinalize(&ctrl.condWait);
ErrorNoSuchThread(interp, thrId);
return TCL_ERROR;
}
tsdPtr->refCount++;
}
Tcl_MutexUnlock(&threadMutex);
Tcl_ConditionFinalize(&ctrl.condWait);
ThreadGetHandle(thrId, thrHandle);
Tcl_SetObjResult(interp, Tcl_NewStringObj(thrHandle, -1));
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* NewThread --
*
* This routine is the "main()" for a new thread whose task is to
* execute a single TCL script. The argument to this function is
* a pointer to a structure that contains the text of the Tcl script
* to be executed, plus some synchronization primitives. Those are
* used so the caller gets signalized when the new thread has
* done its initialization.
*
* Space to hold the ThreadControl structure itself is reserved on
* the stack of the calling function. The two condition variables
* in the ThreadControl structure are destroyed by the calling
* function as well. The calling function will destroy the
* ThreadControl structure and the condition variable as soon as
* ctrlPtr->condWait is signaled, so this routine must make copies
* of any data it might need after that point.
*
* Results:
* none
*
* Side effects:
* A Tcl script is executed in a new thread.
*
*----------------------------------------------------------------------
*/
Tcl_ThreadCreateType
NewThread(clientData)
ClientData clientData;
{
ThreadCtrl *ctrlPtr = (ThreadCtrl *)clientData;
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
Tcl_Interp *interp;
int result = TCL_OK, scriptLen;
char *evalScript;
/*
* Initialize the interpreter. The bad thing here is that we
* assume that initialization of the Tcl interp will be
* error free, which it may not. In the future we must recover
* from this and exit gracefully (this is not that easy as
* it seems on the first glance...)
*/
#ifdef NS_AOLSERVER
NsThreadInterpData *md = (NsThreadInterpData *)ctrlPtr->cd;
Ns_ThreadSetName("-tclthread-");
interp = (Tcl_Interp*)Ns_TclAllocateInterp(md ? md->server : NULL);
#else
interp = Tcl_CreateInterp();
result = Tcl_Init(interp);
#endif
#if !defined(NS_AOLSERVER) || (defined(NS_MAJOR_VERSION) && NS_MAJOR_VERSION >= 4)
result = Thread_Init(interp);
#endif
tsdPtr->interp = interp;
Tcl_MutexLock(&threadMutex);
/*
* Update the list of threads.
*/
ListUpdateInner(tsdPtr);
/*
* We need to keep a pointer to the alloc'ed mem of the script
* we are eval'ing, for the case that we exit during evaluation
*/
scriptLen = strlen(ctrlPtr->script);
evalScript = strcpy((char*)ckalloc(scriptLen+1), ctrlPtr->script);
Tcl_CreateThreadExitHandler(ThreadExitProc,(ClientData)evalScript);
/*
* Notify the parent we are alive.
*/
ctrlPtr->script = NULL;
Tcl_ConditionNotify(&ctrlPtr->condWait);
Tcl_MutexUnlock(&threadMutex);
/*
* Run the script.
*/
Tcl_Preserve((ClientData)tsdPtr->interp);
result = Tcl_EvalEx(tsdPtr->interp, evalScript,scriptLen,TCL_EVAL_GLOBAL);
if (result != TCL_OK) {
ThreadErrorProc(tsdPtr->interp);
}
/*
* Clean up. Note: add something like TlistRemove for the transfer list.
*/
if (tsdPtr->doOneEvent) {
Tcl_ConditionFinalize(&tsdPtr->doOneEvent);
}
ListRemove(tsdPtr);
/*
* It is up to all other extensions, including Tk, to be responsible
* for their own events when they receive their Tcl_CallWhenDeleted
* notice when we delete this interp.
*/
#ifdef NS_AOLSERVER
Ns_TclMarkForDelete(tsdPtr->interp);
Ns_TclDeAllocateInterp(tsdPtr->interp);
#else
Tcl_DeleteInterp(tsdPtr->interp);
#endif
Tcl_Release((ClientData)tsdPtr->interp);
/*tsdPtr->interp = NULL;*/
/*
* Tcl_ExitThread calls Tcl_FinalizeThread() indirectly which calls
* ThreadExitHandlers and cleans the notifier as well as other sub-
* systems that save thread state data.
*/
Tcl_ExitThread(result);
TCL_THREAD_CREATE_RETURN;
}
/*
*----------------------------------------------------------------------
*
* ThreadErrorProc --
*
* Send a message to the thread willing to hear about errors.
*
* Results:
* None
*
* Side effects:
* Send an event.
*
*----------------------------------------------------------------------
*/
static void
ThreadErrorProc(interp)
Tcl_Interp *interp; /* Interp that failed */
{
ThreadSendData *sendPtr;
const char *argv[3];
char buf[THREAD_HNDLMAXLEN];
const char *errorInfo;
errorInfo = Tcl_GetVar2(interp, "errorInfo", NULL, TCL_GLOBAL_ONLY);
if (errorInfo == NULL) {
errorInfo = "";
}
if (errorProcString == NULL) {
#ifdef NS_AOLSERVER
Ns_Log(Error, "%s\n%s", Tcl_GetString(Tcl_GetObjResult(interp)), errorInfo);
#else
Tcl_Channel errChannel = Tcl_GetStdChannel(TCL_STDERR);
if (errChannel == NULL) {
/* Fixes the [#634845] bug; credits to
* Wojciech Kocjan <[email protected]> */
return;
}
ThreadGetHandle(Tcl_GetCurrentThread(), buf);
Tcl_WriteChars(errChannel, "Error from thread ", -1);
Tcl_WriteChars(errChannel, buf, -1);
Tcl_WriteChars(errChannel, "\n", 1);
Tcl_WriteChars(errChannel, errorInfo, -1);
Tcl_WriteChars(errChannel, "\n", 1);
#endif
} else {
ThreadGetHandle(Tcl_GetCurrentThread(), buf);
argv[0] = errorProcString;
argv[1] = buf;
argv[2] = errorInfo;
sendPtr = (ThreadSendData*)ckalloc(sizeof(ThreadSendData));
sendPtr->execProc = ThreadSendEval;
sendPtr->freeProc = threadSendFree;
sendPtr->clientData = (ClientData) Tcl_Merge(3, argv);
sendPtr->interp = NULL;
ThreadSend(interp, errorThreadId, sendPtr, NULL, 0);
}
}
/*
*----------------------------------------------------------------------
*
* ListUpdate --
*
* Add the thread local storage to the list. This grabs the
* mutex to protect the list.
*
* Results:
* None
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
ListUpdate(tsdPtr)
ThreadSpecificData *tsdPtr;
{
if (tsdPtr == NULL) {
tsdPtr = TCL_TSD_INIT(&dataKey);
}
Tcl_MutexLock(&threadMutex);
ListUpdateInner(tsdPtr);
Tcl_MutexUnlock(&threadMutex);
}
/*
*----------------------------------------------------------------------
*
* ListUpdateInner --
*
* Add the thread local storage to the list. This assumes the caller
* has obtained the threadMutex.
*
* Results:
* None
*
* Side effects:
* Add the thread local storage to its list.
*
*----------------------------------------------------------------------
*/
static void
ListUpdateInner(tsdPtr)
ThreadSpecificData *tsdPtr;
{
if (threadList) {
threadList->prevPtr = tsdPtr;
}
tsdPtr->nextPtr = threadList;
tsdPtr->prevPtr = NULL;
tsdPtr->threadId = Tcl_GetCurrentThread();
threadList = tsdPtr;
}
/*
*----------------------------------------------------------------------
*
* ListRemove --
*
* Remove the thread local storage from its list. This grabs the
* mutex to protect the list.
*
* Results:
* None
*
* Side effects:
* Remove the thread local storage from its list.
*
*----------------------------------------------------------------------
*/
static void
ListRemove(tsdPtr)
ThreadSpecificData *tsdPtr;
{
if (tsdPtr == NULL) {
tsdPtr = TCL_TSD_INIT(&dataKey);
}
Tcl_MutexLock(&threadMutex);
ListRemoveInner(tsdPtr);
Tcl_MutexUnlock(&threadMutex);
}
/*
*----------------------------------------------------------------------
*
* ListRemoveInner --
*
* Remove the thread local storage from its list.
*
* Results:
* None
*
* Side effects:
* Remove the thread local storage from its list.
*
*----------------------------------------------------------------------
*/
static void
ListRemoveInner(tsdPtr)
ThreadSpecificData *tsdPtr;
{
if (tsdPtr->prevPtr || tsdPtr->nextPtr) {
if (tsdPtr->prevPtr) {
tsdPtr->prevPtr->nextPtr = tsdPtr->nextPtr;
} else {
threadList = tsdPtr->nextPtr;
}
if (tsdPtr->nextPtr) {
tsdPtr->nextPtr->prevPtr = tsdPtr->prevPtr;
}
tsdPtr->nextPtr = NULL;
tsdPtr->prevPtr = NULL;
} else if (tsdPtr == threadList) {
threadList = NULL;
}
}
/*
*----------------------------------------------------------------------
*
* ThreadList --
*
* Return a list of threads running Tcl interpreters.
*
* Results:
* Number of threads.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ThreadList(interp, thrIdArray)
Tcl_Interp *interp;
Tcl_ThreadId **thrIdArray;
{
int ii, count = 0;
ThreadSpecificData *tsdPtr;
Tcl_MutexLock(&threadMutex);
/*
* First walk; find out how many threads are registered.
* We may avoid this and gain some speed by maintaining
* the counter of allocated structs in the threadList.
*/
for (tsdPtr = threadList; tsdPtr; tsdPtr = tsdPtr->nextPtr) {
count++;
}
if (count == 0) {
Tcl_MutexUnlock(&threadMutex);
return 0;
}
/*
* Allocate storage for passing thread id's to caller
*/
*thrIdArray = (Tcl_ThreadId*)ckalloc(count * sizeof(Tcl_ThreadId));
/*
* Second walk; fill-in the array with thread ID's
*/
for (tsdPtr = threadList, ii = 0; tsdPtr; tsdPtr = tsdPtr->nextPtr, ii++) {
(*thrIdArray)[ii] = tsdPtr->threadId;
}
Tcl_MutexUnlock(&threadMutex);
return count;
}
/*
*----------------------------------------------------------------------
*
* ThreadExists --
*
* Test whether a thread given by it's id is known to us.
*
* Results:
* Pointer to thread specific data structure or
* NULL if no thread with given ID found
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ThreadExists(thrId)
Tcl_ThreadId thrId;
{
ThreadSpecificData *tsdPtr;
Tcl_MutexLock(&threadMutex);
tsdPtr = ThreadExistsInner(thrId);
Tcl_MutexUnlock(&threadMutex);
return tsdPtr != NULL;
}
/*
*----------------------------------------------------------------------
*
* ThreadExistsInner --
*
* Test whether a thread given by it's id is known to us. Assumes
* caller holds the thread mutex.
*
* Results:
* Pointer to thread specific data structure or
* NULL if no thread with given ID found
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static ThreadSpecificData *
ThreadExistsInner(thrId)
Tcl_ThreadId thrId; /* Thread id to look for. */
{
ThreadSpecificData *tsdPtr;
for (tsdPtr = threadList; tsdPtr; tsdPtr = tsdPtr->nextPtr) {
if (tsdPtr->threadId == thrId) {
return tsdPtr;
}
}
return NULL;
}
#ifdef TCL_TIP285
/*
*----------------------------------------------------------------------
*
* ThreadCancel --
*
* Cancels a script in another thread.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ThreadCancel(interp, thrId, result, flags)
Tcl_Interp *interp; /* The current interpreter. */
Tcl_ThreadId thrId; /* Thread ID of other interpreter. */
const char *result; /* The error message or NULL for default. */
int flags; /* Flags for Tcl_CancelEval. */
{
int code;
Tcl_Obj *resultObj = NULL;
ThreadSpecificData *tsdPtr; /* ... of the target thread */
Tcl_MutexLock(&threadMutex);
tsdPtr = ThreadExistsInner(thrId);
if (tsdPtr == (ThreadSpecificData*)NULL) {
Tcl_MutexUnlock(&threadMutex);
ErrorNoSuchThread(interp, thrId);
return TCL_ERROR;
}
if (!haveInterpCancel) {
Tcl_MutexUnlock(&threadMutex);
Tcl_AppendResult(interp, "not supported with this Tcl version", NULL);
return TCL_ERROR;
}
if (result != NULL) {
resultObj = Tcl_NewStringObj(result, -1);
}
code = Tcl_CancelEval(tsdPtr->interp, resultObj, NULL, flags);
Tcl_MutexUnlock(&threadMutex);
return code;
}
#endif
/*
*----------------------------------------------------------------------
*
* ThreadJoin --
*
* Wait for the exit of a different thread.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* The status of the exiting thread is left in the interp result
* area, but only in the case of success.
*
*----------------------------------------------------------------------
*/
static int
ThreadJoin(interp, thrId)
Tcl_Interp *interp; /* The current interpreter. */
Tcl_ThreadId thrId; /* Thread ID of other interpreter. */
{
int ret, state;
ret = Tcl_JoinThread(thrId, &state);
if (ret == TCL_OK) {
Tcl_SetIntObj(Tcl_GetObjResult (interp), state);
} else {
char thrHandle[THREAD_HNDLMAXLEN];
ThreadGetHandle(thrId, thrHandle);
Tcl_AppendResult(interp, "cannot join thread ", thrHandle, NULL);
}
return ret;
}
/*
*----------------------------------------------------------------------
*
* ThreadTransfer --
*
* Transfers the specified channel which must not be shared and has
* to be registered in the given interp from that location to the
* main interp of the specified thread.
*
* Thanks to Anreas Kupries for the initial implementation.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* The thread-global lists of all known channels of both threads
* involved (specified and current) are modified. The channel is
* moved, all event handling for the channel is killed.
*
*----------------------------------------------------------------------
*/
static int
ThreadTransfer(interp, thrId, chan)
Tcl_Interp *interp; /* The current interpreter. */
Tcl_ThreadId thrId; /* Thread Id of other interpreter. */
Tcl_Channel chan; /* The channel to transfer */
{
/* Steps to perform for the transfer:
*
* i. Sanity checks: chan has to registered in interp, must not be
* shared. This automatically excludes the special channels for
* stdin, stdout and stderr!
* ii. Clear event handling.
* iii. Bump reference counter up to prevent destruction during the
* following unregister, then unregister the channel from the
* interp. Remove it from the thread-global list of all channels
* too.
* iv. Wrap the channel into an event and send that to the other
* thread, then wait for the other thread to process our message.
* v. The event procedure called by the other thread is
* 'TransferEventProc'. It links the channel into the
* thread-global list of channels for that thread, registers it
* in the main interp of the other thread, removes the artificial
* reference, at last notifies this thread of the sucessful
* transfer. This allows this thread then to proceed.
*/
TransferEvent *evPtr;
TransferResult *resultPtr;
if (!Tcl_IsChannelRegistered(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("channel is not registered here", -1));
}
if (Tcl_IsChannelShared(chan)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("channel is shared", -1));
return TCL_ERROR;
}
/*
* Short circuit transfers to ourself. Nothing to do.
*/
if (thrId == Tcl_GetCurrentThread()) {
return TCL_OK;
}
Tcl_MutexLock(&threadMutex);
/*
* Verify the thread exists.
*/
if (ThreadExistsInner(thrId) == NULL) {
Tcl_MutexUnlock(&threadMutex);
ErrorNoSuchThread(interp, thrId);
return TCL_ERROR;
}
/*
* Cut the channel out of the interp/thread
*/
ThreadCutChannel(interp, chan);
/*
* Wrap it into an event.
*/
resultPtr = (TransferResult*)ckalloc(sizeof(TransferResult));
evPtr = (TransferEvent *)ckalloc(sizeof(TransferEvent));
evPtr->chan = chan;
evPtr->event.proc = TransferEventProc;
evPtr->resultPtr = resultPtr;
/*
* Initialize the result fields.
*/
resultPtr->done = (Tcl_Condition) NULL;
resultPtr->resultCode = -1;
resultPtr->resultMsg = (char *) NULL;
/*
* Maintain the cleanup list.
*/
resultPtr->srcThreadId = Tcl_GetCurrentThread();
resultPtr->dstThreadId = thrId;
resultPtr->eventPtr = evPtr;
SpliceIn(resultPtr, transferList);
/*
* Queue the event and poke the other thread's notifier.
*/
Tcl_ThreadQueueEvent(thrId, (Tcl_Event*)evPtr, TCL_QUEUE_TAIL);
Tcl_ThreadAlert(thrId);
/*
* (*) Block until the other thread has either processed the transfer
* or rejected it.
*/
while (resultPtr->resultCode < 0) {
Tcl_ConditionWait(&resultPtr->done, &threadMutex, NULL);
}
/*
* Unlink result from the result list.
*/
SpliceOut(resultPtr, transferList);
resultPtr->eventPtr = NULL;
resultPtr->nextPtr = NULL;
resultPtr->prevPtr = NULL;
Tcl_MutexUnlock(&threadMutex);
Tcl_ConditionFinalize(&resultPtr->done);
/*
* Process the result now.
*/
if (resultPtr->resultCode != TCL_OK) {
/*
* Transfer failed, restore old state of channel with respect
* to current thread and specified interp.
*/
Tcl_SpliceChannel(chan);
Tcl_RegisterChannel(interp, chan);
Tcl_UnregisterChannel((Tcl_Interp *) NULL, chan);
Tcl_AppendResult(interp, "transfer failed: ", NULL);
if (resultPtr->resultMsg) {
Tcl_AppendResult(interp, resultPtr->resultMsg, NULL);
ckfree(resultPtr->resultMsg);
} else {
Tcl_AppendResult(interp, "for reasons unknown", NULL);
}
ckfree((char *)resultPtr);
return TCL_ERROR;
}
if (resultPtr->resultMsg) {
ckfree(resultPtr->resultMsg);
}
ckfree((char *)resultPtr);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadDetach --
*
* Detaches the specified channel which must not be shared and has
* to be registered in the given interp. The detached channel is
* left in the transfer list until some other thread attaches it
+ by calling the "thread::attach" command.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* The thread-global lists of all known channels (transferList)
* is modified. All event handling for the channel is killed.
*
*----------------------------------------------------------------------
*/
static int
ThreadDetach(interp, chan)
Tcl_Interp *interp; /* The current interpreter. */
Tcl_Channel chan; /* The channel to detach */
{
TransferEvent *evPtr;
TransferResult *resultPtr;
if (!Tcl_IsChannelRegistered(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("channel is not registered here", -1));
}
if (Tcl_IsChannelShared(chan)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("channel is shared", -1));
return TCL_ERROR;
}
/*
* Cut the channel out of the interp/thread
*/
ThreadCutChannel(interp, chan);
/*
* Wrap it into the list of transfered channels. We generate no
* events associated with the detached channel, thus really not
* needing the transfer event structure allocated here. This
* is done purely to avoid having yet another wrapper.
*/
resultPtr = (TransferResult*)ckalloc(sizeof(TransferResult));
evPtr = (TransferEvent*)ckalloc(sizeof(TransferEvent));
evPtr->chan = chan;
evPtr->event.proc = NULL;
evPtr->resultPtr = resultPtr;
/*
* Initialize the result fields. This is not used.
*/
resultPtr->done = (Tcl_Condition)NULL;
resultPtr->resultCode = -1;
resultPtr->resultMsg = (char*)NULL;
/*
* Maintain the cleanup list. By setting the dst/srcThreadId
* to zero we signal the code in ThreadAttach that this is the
* detached channel. Therefore it should not be mistaken for
* some regular TransferChannel operation underway. Also, this
* will prevent the code in ThreadExitProc to splice out this
* record from the list when the threads are exiting.
* A side effect of this is that we may have entries in this
* list which may never be removed (i.e. nobody attaches the
* channel later on). This will result in both Tcl channel and
* memory leak.
*/
resultPtr->srcThreadId = (Tcl_ThreadId)0;
resultPtr->dstThreadId = (Tcl_ThreadId)0;
resultPtr->eventPtr = evPtr;
Tcl_MutexLock(&threadMutex);
SpliceIn(resultPtr, transferList);
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadAttach --
*
* Attaches the previously detached channel into the current
* interpreter.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* The thread-global lists of all known channels (transferList)
* is modified.
*
*----------------------------------------------------------------------
*/
static int
ThreadAttach(interp, chanName)
Tcl_Interp *interp; /* The current interpreter. */
char *chanName; /* The name of the channel to detach */
{
int found = 0;
Tcl_Channel chan = NULL;
TransferResult *resPtr;
/*
* Locate the channel to attach by looking up its name in
* the list of transfered channels. Watch that we don't
* hit the regular channel transfer event.
*/
Tcl_MutexLock(&threadMutex);
for (resPtr = transferList; resPtr; resPtr = resPtr->nextPtr) {
chan = resPtr->eventPtr->chan;
if (!strcmp(Tcl_GetChannelName(chan),chanName)
&& !resPtr->dstThreadId) {
if (Tcl_IsChannelExisting(chanName)) {
Tcl_MutexUnlock(&threadMutex);
Tcl_AppendResult(interp, "channel already exists", NULL);
return TCL_ERROR;
}
SpliceOut(resPtr, transferList);
ckfree((char*)resPtr->eventPtr);
ckfree((char*)resPtr);
found = 1;
break;
}
}
Tcl_MutexUnlock(&threadMutex);
if (found == 0) {
Tcl_AppendResult(interp, "channel not detached", NULL);
return TCL_ERROR;
}
/*
* Splice channel into the current interpreter
*/
Tcl_SpliceChannel(chan);
Tcl_RegisterChannel(interp, chan);
Tcl_UnregisterChannel((Tcl_Interp *)NULL, chan);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadSend --
*
* Run the procedure in other thread.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ThreadSend(interp, thrId, send, clbk, flags)
Tcl_Interp *interp; /* The current interpreter. */
Tcl_ThreadId thrId; /* Thread Id of other thread. */
ThreadSendData *send; /* Pointer to structure with work to do */
ThreadClbkData *clbk; /* Opt. callback structure (may be NULL) */
int flags; /* Wait or queue to tail */
{
ThreadSpecificData *tsdPtr = NULL; /* ... of the target thread */
int code;
ThreadEvent *eventPtr;
ThreadEventResult *resultPtr;
/*
* Verify the thread exists and is not in the error state.
* The thread is in the error state only if we've configured
* it to unwind on script evaluation error and last script
* evaluation resulted in error actually.
*/
Tcl_MutexLock(&threadMutex);
tsdPtr = ThreadExistsInner(thrId);
if (tsdPtr == (ThreadSpecificData*)NULL
|| (tsdPtr->flags & THREAD_FLAGS_INERROR)) {
int inerror = tsdPtr && (tsdPtr->flags & THREAD_FLAGS_INERROR);
Tcl_MutexUnlock(&threadMutex);
ThreadFreeProc((ClientData)send);
if (clbk) {
ThreadFreeProc((ClientData)clbk);
}
if (inerror) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("thread is in error", -1));
} else {
ErrorNoSuchThread(interp, thrId);
}
return TCL_ERROR;
}
/*
* Short circuit sends to ourself.
*/
if (thrId == Tcl_GetCurrentThread()) {
Tcl_MutexUnlock(&threadMutex);
if ((flags & THREAD_SEND_WAIT)) {
int code = (*send->execProc)(interp, (ClientData)send);
ThreadFreeProc((ClientData)send);
return code;
} else {
send->interp = interp;
Tcl_Preserve((ClientData)send->interp);
Tcl_DoWhenIdle((Tcl_IdleProc*)ThreadIdleProc, (ClientData)send);
return TCL_OK;
}
}
/*
* Create the event for target thread event queue.
*/
eventPtr = (ThreadEvent*)ckalloc(sizeof(ThreadEvent));
eventPtr->sendData = send;
eventPtr->clbkData = clbk;
/*
* Target thread about to service
* another event
*/
if (tsdPtr->maxEventsCount) {
tsdPtr->eventsPending++;
}
/*
* Caller wants to be notified, so we must take care
* it's interpreter stays alive until we've finished.
*/
if (eventPtr->clbkData) {
Tcl_Preserve((ClientData)eventPtr->clbkData->interp);
}
if ((flags & THREAD_SEND_WAIT) == 0) {
resultPtr = NULL;
eventPtr->resultPtr = NULL;
} else {
resultPtr = (ThreadEventResult*)ckalloc(sizeof(ThreadEventResult));
resultPtr->done = (Tcl_Condition)NULL;
resultPtr->result = NULL;
resultPtr->errorCode = NULL;
resultPtr->errorInfo = NULL;
resultPtr->dstThreadId = thrId;
resultPtr->srcThreadId = Tcl_GetCurrentThread();
resultPtr->eventPtr = eventPtr;
eventPtr->resultPtr = resultPtr;
SpliceIn(resultPtr, resultList);
}
/*
* Queue the event and poke the other thread's notifier.
*/
eventPtr->event.proc = ThreadEventProc;
if ((flags & THREAD_SEND_HEAD)) {
Tcl_ThreadQueueEvent(thrId, (Tcl_Event*)eventPtr, TCL_QUEUE_HEAD);
} else {
Tcl_ThreadQueueEvent(thrId, (Tcl_Event*)eventPtr, TCL_QUEUE_TAIL);
}
Tcl_ThreadAlert(thrId);
if ((flags & THREAD_SEND_WAIT) == 0) {
/*
* Might potentially spend some time here, until the
* worker thread cleans up its queue a little bit.
*/
if ((flags & THREAD_SEND_CLBK) == 0) {
while (tsdPtr->maxEventsCount &&
tsdPtr->eventsPending > tsdPtr->maxEventsCount) {
Tcl_ConditionWait(&tsdPtr->doOneEvent, &threadMutex, NULL);
}
}
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
/*
* Block on the result indefinitely.
*/
Tcl_ResetResult(interp);
while (resultPtr->result == NULL) {
Tcl_ConditionWait(&resultPtr->done, &threadMutex, NULL);
}
SpliceOut(resultPtr, resultList);
Tcl_MutexUnlock(&threadMutex);
/*
* Return result to caller
*/
if (resultPtr->code == TCL_ERROR) {
if (resultPtr->errorCode) {
Tcl_SetErrorCode(interp, resultPtr->errorCode, NULL);
ckfree(resultPtr->errorCode);
}
if (resultPtr->errorInfo) {
Tcl_AddErrorInfo(interp, resultPtr->errorInfo);
ckfree(resultPtr->errorInfo);
}
}
code = resultPtr->code;
Tcl_SetObjResult(interp, Tcl_NewStringObj(resultPtr->result, -1));
/*
* Cleanup
*/
Tcl_ConditionFinalize(&resultPtr->done);
if (resultPtr->result != threadEmptyResult) {
ckfree(resultPtr->result);
}
ckfree((char*)resultPtr);
return code;
}
/*
*----------------------------------------------------------------------
*
* ThreadWait --
*
* Waits for events and process them as they come, until signaled
* to stop.
*
* Results:
* Standard Tcl result.
*
* Side effects:
* Deletes any thread::send or thread::transfer events that are
* pending.
*
*----------------------------------------------------------------------
*/
static int
ThreadWait(Tcl_Interp *interp)
{
int code = TCL_OK;
int canrun = 1;
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
/*
* Process events until signaled to stop.
*/
while (canrun) {
/*
* About to service another event.
* Wake-up eventual sleepers.
*/
if (tsdPtr->maxEventsCount) {
Tcl_MutexLock(&threadMutex);
tsdPtr->eventsPending--;
Tcl_ConditionNotify(&tsdPtr->doOneEvent);
Tcl_MutexUnlock(&threadMutex);
}
/*
* Attempt to process one event, blocking forever until an
* event is actually received. The event processed may cause
* a script in progress to be canceled or exceed its limit;
* therefore, check for these conditions if we are able to
* (i.e. we are running in a high enough version of Tcl).
*/
Tcl_DoOneEvent(TCL_ALL_EVENTS);
#ifdef TCL_TIP285
if (haveInterpCancel) {
/*
* If the script has been unwound, bail out immediately. This does
* not follow the recommended guidelines for how extensions should
* handle the script cancellation functionality because this is
* not a "normal" extension. Most extensions do not have a command
* that simply enters an infinite Tcl event loop. Normal extensions
* should not specify the TCL_CANCEL_UNWIND when calling the
* Tcl_Canceled function to check if the command has been canceled.
*/
if (Tcl_Canceled(tsdPtr->interp,
TCL_LEAVE_ERR_MSG | TCL_CANCEL_UNWIND) == TCL_ERROR) {
code = TCL_ERROR;
break;
}
}
#endif
#ifdef TCL_TIP143
if (haveInterpLimit) {
if (Tcl_LimitExceeded(tsdPtr->interp)) {
code = TCL_ERROR;
break;
}
}
#endif
/*
* Test stop condition under mutex since
* some other thread may flip our flags.
*/
Tcl_MutexLock(&threadMutex);
canrun = (tsdPtr->flags & THREAD_FLAGS_STOPPED) == 0;
Tcl_MutexUnlock(&threadMutex);
}
#if defined(TCL_TIP143) || defined(TCL_TIP285)
/*
* If the event processing loop above was terminated due to a
* script in progress being canceled or exceeding its limits,
* transfer the error to the current interpreter.
*/
if (code != TCL_OK) {
char buf[THREAD_HNDLMAXLEN];
const char *errorInfo;
errorInfo = Tcl_GetVar2(tsdPtr->interp, "errorInfo", NULL, TCL_GLOBAL_ONLY);
if (errorInfo == NULL) {
errorInfo = Tcl_GetString(Tcl_GetObjResult(tsdPtr->interp));
}
ThreadGetHandle(Tcl_GetCurrentThread(), buf);
Tcl_AppendResult(interp, "Error from thread ", buf, "\n",
errorInfo, NULL);
}
#endif
/*
* Remove from the list of active threads, so nobody can post
* work to this thread, since it is just about to terminate.
*/
ListRemove(tsdPtr);
/*
* Now that the event processor for this thread is closing,
* delete all pending thread::send and thread::transfer events.
* These events are owned by us. We don't delete anyone else's
* events, but ours.
*/
Tcl_DeleteEvents((Tcl_EventDeleteProc*)ThreadDeleteEvent, NULL);
return code;
}
/*
*----------------------------------------------------------------------
*
* ThreadReserve --
*
* Results:
*
* Side effects:
*
*----------------------------------------------------------------------
*/
static int
ThreadReserve(interp, thrId, operation, wait)
Tcl_Interp *interp; /* Current interpreter */
Tcl_ThreadId thrId; /* Target thread ID */
int operation; /* THREAD_RESERVE | THREAD_RELEASE */
int wait; /* Wait for thread to exit */
{
int users, dowait = 0;
ThreadEvent *evPtr;
ThreadSpecificData *tsdPtr;
Tcl_MutexLock(&threadMutex);
/*
* Check the given thread
*/
if (thrId == (Tcl_ThreadId)0) {
tsdPtr = TCL_TSD_INIT(&dataKey);
} else {
tsdPtr = ThreadExistsInner(thrId);
if (tsdPtr == (ThreadSpecificData*)NULL) {
Tcl_MutexUnlock(&threadMutex);
ErrorNoSuchThread(interp, thrId);
return TCL_ERROR;
}
}
switch (operation) {
case THREAD_RESERVE: ++tsdPtr->refCount; break;
case THREAD_RELEASE: --tsdPtr->refCount; dowait = wait; break;
}
users = tsdPtr->refCount;
if (users <= 0) {
/*
* We're last attached user, so tear down the *target* thread
*/
tsdPtr->flags |= THREAD_FLAGS_STOPPED;
if (thrId && thrId != Tcl_GetCurrentThread() /* Not current! */) {
ThreadEventResult *resultPtr = NULL;
/*
* Remove from the list of active threads, so nobody can post
* work to this thread, since it is just about to terminate.
*/
ListRemoveInner(tsdPtr);
/*
* Send an dummy event, just to wake-up target thread.
* It should immediately exit thereafter. We might get
* stuck here for long time if user really wants to
* be absolutely sure that the thread has exited.
*/
if (dowait) {
resultPtr = (ThreadEventResult*)
ckalloc(sizeof(ThreadEventResult));
resultPtr->done = (Tcl_Condition)NULL;
resultPtr->result = NULL;
resultPtr->code = TCL_OK;
resultPtr->errorCode = NULL;
resultPtr->errorInfo = NULL;
resultPtr->dstThreadId = thrId;
resultPtr->srcThreadId = Tcl_GetCurrentThread();
SpliceIn(resultPtr, resultList);
}
evPtr = (ThreadEvent*)ckalloc(sizeof(ThreadEvent));
evPtr->event.proc = ThreadEventProc;
evPtr->sendData = NULL;
evPtr->clbkData = NULL;
evPtr->resultPtr = resultPtr;
Tcl_ThreadQueueEvent(thrId, (Tcl_Event*)evPtr, TCL_QUEUE_TAIL);
Tcl_ThreadAlert(thrId);
if (dowait) {
while (resultPtr->result == NULL) {
Tcl_ConditionWait(&resultPtr->done, &threadMutex, NULL);
}
SpliceOut(resultPtr, resultList);
Tcl_ConditionFinalize(&resultPtr->done);
if (resultPtr->result != threadEmptyResult) {
ckfree(resultPtr->result); /* Will be ignored anyway */
}
ckfree((char*)resultPtr);
}
}
}
Tcl_MutexUnlock(&threadMutex);
Tcl_SetIntObj(Tcl_GetObjResult(interp), (users > 0) ? users : 0);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadEventProc --
*
* Handle the event in the target thread.
*
* Results:
* Returns 1 to indicate that the event was processed.
*
* Side effects:
* Fills out the ThreadEventResult struct.
*
*----------------------------------------------------------------------
*/
static int
ThreadEventProc(evPtr, mask)
Tcl_Event *evPtr; /* Really ThreadEvent */
int mask;
{
ThreadSpecificData* tsdPtr = TCL_TSD_INIT(&dataKey);
Tcl_Interp *interp = NULL;
Tcl_ThreadId thrId = Tcl_GetCurrentThread();
ThreadEvent *eventPtr = (ThreadEvent*)evPtr;
ThreadSendData *sendPtr = eventPtr->sendData;
ThreadClbkData *clbkPtr = eventPtr->clbkData;
ThreadEventResult* resultPtr = eventPtr->resultPtr;
int code = TCL_ERROR; /* Pessimistic assumption */
/*
* See whether user has any preferences about which interpreter
* to use for running this job. The job structure might identify
* one. If not, just use the thread's main interpreter which is
* stored in the thread specific data structure.
* Note that later on we might discover that we're running the
* async callback script. In this case, interpreter will be
* changed to one given in the callback.
*/
interp = (sendPtr && sendPtr->interp) ? sendPtr->interp : tsdPtr->interp;
if (interp != NULL) {
Tcl_Preserve((ClientData)interp);
if (clbkPtr && clbkPtr->threadId == thrId) {
Tcl_Release((ClientData)interp);
/* Watch: this thread evaluates its own callback. */
interp = clbkPtr->interp;
Tcl_Preserve((ClientData)interp);
}
Tcl_ResetResult(interp);
if (sendPtr) {
Tcl_CreateThreadExitHandler(ThreadFreeProc, (ClientData)sendPtr);
if (clbkPtr) {
Tcl_CreateThreadExitHandler(ThreadFreeProc,
(ClientData)clbkPtr);
}
code = (*sendPtr->execProc)(interp, (ClientData)sendPtr);
Tcl_DeleteThreadExitHandler(ThreadFreeProc, (ClientData)sendPtr);
if (clbkPtr) {
Tcl_DeleteThreadExitHandler(ThreadFreeProc,
(ClientData)clbkPtr);
}
} else {
code = TCL_OK;
}
}
if (sendPtr) {
ThreadFreeProc((ClientData)sendPtr);
eventPtr->sendData = NULL;
}
if (resultPtr) {
/*
* Report job result synchronously to waiting caller
*/
Tcl_MutexLock(&threadMutex);
ThreadSetResult(interp, code, resultPtr);
Tcl_ConditionNotify(&resultPtr->done);
Tcl_MutexUnlock(&threadMutex);
/*
* We still need to release the reference to the Tcl
* interpreter added by ThreadSend whenever the callback
* data is not NULL.
*/
if (clbkPtr) {
Tcl_Release((ClientData)clbkPtr->interp);
}
} else if (clbkPtr && clbkPtr->threadId != thrId) {
ThreadSendData *tmpPtr = (ThreadSendData*)clbkPtr;
/*
* Route the callback back to it's originator.
* Do not wait for the result.
*/
if (code != TCL_OK) {
ThreadErrorProc(interp);
}
ThreadSetResult(interp, code, &clbkPtr->result);
ThreadSend(interp, clbkPtr->threadId, tmpPtr, NULL, THREAD_SEND_CLBK);
} else if (code != TCL_OK) {
/*
* Only pass errors onto the registered error handler
* when we don't have a result target for this event.
*/
ThreadErrorProc(interp);
/*
* We still need to release the reference to the Tcl
* interpreter added by ThreadSend whenever the callback
* data is not NULL.
*/
if (clbkPtr) {
Tcl_Release((ClientData)clbkPtr->interp);
}
} else {
/*
* We still need to release the reference to the Tcl
* interpreter added by ThreadSend whenever the callback
* data is not NULL.
*/
if (clbkPtr) {
Tcl_Release((ClientData)clbkPtr->interp);
}
}
if (interp != NULL) {
Tcl_Release((ClientData)interp);
}
/*
* Mark unwind scenario for this thread if the script resulted
* in error condition and thread has been marked to unwind.
* This will cause thread to disappear from the list of active
* threads, clean-up its event queue and exit.
*/
if (code != TCL_OK) {
Tcl_MutexLock(&threadMutex);
if (tsdPtr->flags & THREAD_FLAGS_UNWINDONERROR) {
tsdPtr->flags |= THREAD_FLAGS_INERROR;
if (tsdPtr->refCount == 0) {
tsdPtr->flags |= THREAD_FLAGS_STOPPED;
}
}
Tcl_MutexUnlock(&threadMutex);
}
return 1;
}
/*
*----------------------------------------------------------------------
*
* ThreadSetResult --
*
* Results:
*
* Side effects:
*
*----------------------------------------------------------------------
*/
static void
ThreadSetResult(interp, code, resultPtr)
Tcl_Interp *interp;
int code;
ThreadEventResult *resultPtr;
{
size_t reslen;
const char *errorCode, *errorInfo, *result;
if (interp == NULL) {
code = TCL_ERROR;
errorInfo = "";
errorCode = "THREAD";
result = "no target interp!";
reslen = strlen(result);
resultPtr->result = (reslen) ?
strcpy(ckalloc(1+reslen), result) : threadEmptyResult;
} else {
result = Tcl_GetString(Tcl_GetObjResult(interp));
reslen = Tcl_GetObjResult(interp)->length;
resultPtr->result = (reslen) ?
strcpy(ckalloc(1+reslen), result) : threadEmptyResult;
if (code == TCL_ERROR) {
errorCode = Tcl_GetVar2(interp, "errorCode", NULL, TCL_GLOBAL_ONLY);
errorInfo = Tcl_GetVar2(interp, "errorInfo", NULL, TCL_GLOBAL_ONLY);
} else {
errorCode = NULL;
errorInfo = NULL;
}
}
resultPtr->code = code;
if (errorCode != NULL) {
resultPtr->errorCode = ckalloc(1+strlen(errorCode));
strcpy(resultPtr->errorCode, errorCode);
} else {
resultPtr->errorCode = NULL;
}
if (errorInfo != NULL) {
resultPtr->errorInfo = ckalloc(1+strlen(errorInfo));
strcpy(resultPtr->errorInfo, errorInfo);
} else {
resultPtr->errorInfo = NULL;
}
}
/*
*----------------------------------------------------------------------
*
* ThreadGetOption --
*
* Results:
*
* Side effects:
*
*----------------------------------------------------------------------
*/
static int
ThreadGetOption(interp, thrId, option, dsPtr)
Tcl_Interp *interp;
Tcl_ThreadId thrId;
char *option;
Tcl_DString *dsPtr;
{
int len;
ThreadSpecificData *tsdPtr = NULL;
/*
* If the optionName is NULL it means that we want
* a list of all options and values.
*/
len = (option == NULL) ? 0 : strlen(option);
Tcl_MutexLock(&threadMutex);
tsdPtr = ThreadExistsInner(thrId);
if (tsdPtr == (ThreadSpecificData*)NULL) {
Tcl_MutexUnlock(&threadMutex);
ErrorNoSuchThread(interp, thrId);
return TCL_ERROR;
}
if (len == 0 || (len > 3 && option[1] == 'e' && option[2] == 'v'
&& !strncmp(option,"-eventmark", len))) {
char buf[16];
if (len == 0) {
Tcl_DStringAppendElement(dsPtr, "-eventmark");
}
sprintf(buf, "%d", tsdPtr->maxEventsCount);
Tcl_DStringAppendElement(dsPtr, buf);
if (len != 0) {
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
}
if (len == 0 || (len > 2 && option[1] == 'u'
&& !strncmp(option,"-unwindonerror", len))) {
int flag = tsdPtr->flags & THREAD_FLAGS_UNWINDONERROR;
if (len == 0) {
Tcl_DStringAppendElement(dsPtr, "-unwindonerror");
}
Tcl_DStringAppendElement(dsPtr, flag ? "1" : "0");
if (len != 0) {
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
}
if (len == 0 || (len > 3 && option[1] == 'e' && option[2] == 'r'
&& !strncmp(option,"-errorstate", len))) {
int flag = tsdPtr->flags & THREAD_FLAGS_INERROR;
if (len == 0) {
Tcl_DStringAppendElement(dsPtr, "-errorstate");
}
Tcl_DStringAppendElement(dsPtr, flag ? "1" : "0");
if (len != 0) {
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
}
if (len != 0) {
Tcl_AppendResult(interp, "bad option \"", option,
"\", should be one of -eventmark, "
"-unwindonerror or -errorstate", NULL);
Tcl_MutexUnlock(&threadMutex);
return TCL_ERROR;
}
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadSetOption --
*
* Results:
*
* Side effects:
*
*----------------------------------------------------------------------
*/
static int
ThreadSetOption(interp, thrId, option, value)
Tcl_Interp *interp;
Tcl_ThreadId thrId;
char *option;
char *value;
{
int len = strlen(option);
ThreadSpecificData *tsdPtr = NULL;
Tcl_MutexLock(&threadMutex);
tsdPtr = ThreadExistsInner(thrId);
if (tsdPtr == (ThreadSpecificData*)NULL) {
Tcl_MutexUnlock(&threadMutex);
ErrorNoSuchThread(interp, thrId);
return TCL_ERROR;
}
if (len > 3 && option[1] == 'e' && option[2] == 'v'
&& !strncmp(option,"-eventmark", len)) {
if (sscanf(value, "%d", &tsdPtr->maxEventsCount) != 1) {
Tcl_AppendResult(interp, "expected integer but got \"",
value, "\"", NULL);
Tcl_MutexUnlock(&threadMutex);
return TCL_ERROR;
}
} else if (len > 2 && option[1] == 'u'
&& !strncmp(option,"-unwindonerror", len)) {
int flag = 0;
if (Tcl_GetBoolean(interp, value, &flag) != TCL_OK) {
Tcl_MutexUnlock(&threadMutex);
return TCL_ERROR;
}
if (flag) {
tsdPtr->flags |= THREAD_FLAGS_UNWINDONERROR;
} else {
tsdPtr->flags &= ~THREAD_FLAGS_UNWINDONERROR;
}
} else if (len > 3 && option[1] == 'e' && option[2] == 'r'
&& !strncmp(option,"-errorstate", len)) {
int flag = 0;
if (Tcl_GetBoolean(interp, value, &flag) != TCL_OK) {
Tcl_MutexUnlock(&threadMutex);
return TCL_ERROR;
}
if (flag) {
tsdPtr->flags |= THREAD_FLAGS_INERROR;
} else {
tsdPtr->flags &= ~THREAD_FLAGS_INERROR;
}
}
Tcl_MutexUnlock(&threadMutex);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ThreadIdleProc --
*
* Results:
*
* Side effects.
*
*----------------------------------------------------------------------
*/
static void
ThreadIdleProc(clientData)
ClientData clientData;
{
int ret;
ThreadSendData *sendPtr = (ThreadSendData*)clientData;
ret = (*sendPtr->execProc)(sendPtr->interp, (ClientData)sendPtr);
if (ret != TCL_OK) {
ThreadErrorProc(sendPtr->interp);
}
Tcl_Release((ClientData)sendPtr->interp);
ThreadFreeProc(clientData);
}
/*
*----------------------------------------------------------------------
*
* TransferEventProc --
*
* Handle a transfer event in the target thread.
*
* Results:
* Returns 1 to indicate that the event was processed.
*
* Side effects:
* Fills out the TransferResult struct.
*
*----------------------------------------------------------------------
*/
static int
TransferEventProc(evPtr, mask)
Tcl_Event *evPtr; /* Really ThreadEvent */
int mask;
{
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
TransferEvent *eventPtr = (TransferEvent *)evPtr;
TransferResult *resultPtr = eventPtr->resultPtr;
Tcl_Interp *interp = tsdPtr->interp;
int code;
const char* msg = NULL;
if (interp == NULL) {
/*
* Reject transfer in case of a missing target.
*/
code = TCL_ERROR;
msg = "target interp missing";
} else {
/*
* Add channel to current thread and interp.
* See ThreadTransfer for more explanations.
*/
if (Tcl_IsChannelExisting(Tcl_GetChannelName(eventPtr->chan))) {
/*
* Reject transfer. Channel of same name already exists in target.
*/
code = TCL_ERROR;
msg = "channel already exists in target";
} else {
Tcl_SpliceChannel(eventPtr->chan);
Tcl_RegisterChannel(interp, eventPtr->chan);
Tcl_UnregisterChannel((Tcl_Interp *) NULL, eventPtr->chan);
code = TCL_OK; /* Return success. */
}
}
if (resultPtr) {
Tcl_MutexLock(&threadMutex);
resultPtr->resultCode = code;
if (msg != NULL) {
resultPtr->resultMsg = (char*)ckalloc(1+strlen (msg));
strcpy (resultPtr->resultMsg, msg);
}
Tcl_ConditionNotify(&resultPtr->done);
Tcl_MutexUnlock(&threadMutex);
}
return 1;
}
/*
*----------------------------------------------------------------------
*
* ThreadFreeProc --
*
* Called when we are exiting and memory needs to be freed.
*
* Results:
* None.
*
* Side effects:
* Clears up mem specified in ClientData
*
*----------------------------------------------------------------------
*/
static void
ThreadFreeProc(clientData)
ClientData clientData;
{
/*
* This will free send and/or callback structures
* since both are the same in the beginning.
*/
ThreadSendData *anyPtr = (ThreadSendData*)clientData;
if (anyPtr) {
if (anyPtr->clientData) {
(*anyPtr->freeProc)(anyPtr->clientData);
}
ckfree((char*)anyPtr);
}
}
/*
*----------------------------------------------------------------------
*
* ThreadDeleteEvent --
*
* This is called from the ThreadExitProc to delete memory related
* to events that we put on the queue.
*
* Results:
* 1 it was our event and we want it removed, 0 otherwise.
*
* Side effects:
* It cleans up our events in the event queue for this thread.
*
*----------------------------------------------------------------------
*/
static int
ThreadDeleteEvent(eventPtr, clientData)
Tcl_Event *eventPtr; /* Really ThreadEvent */
ClientData clientData; /* dummy */
{
if (eventPtr->proc == ThreadEventProc) {
/*
* Regular script event. Just dispose memory
*/
ThreadEvent *evPtr = (ThreadEvent*)eventPtr;
if (evPtr->sendData) {
ThreadFreeProc((ClientData)evPtr->sendData);
evPtr->sendData = NULL;
}
if (evPtr->clbkData) {
ThreadFreeProc((ClientData)evPtr->clbkData);
evPtr->clbkData = NULL;
}
return 1;
}
if (eventPtr->proc == TransferEventProc) {
/*
* A channel is in flight toward the thread just exiting.
* Pass it back to the originator, if possible.
* Else kill it.
*/
TransferEvent* evPtr = (TransferEvent *) eventPtr;
if (evPtr->resultPtr == (TransferResult *) NULL) {
/* No thread to pass the channel back to. Kill it.
* This requires to splice it temporarily into our channel
* list and then forcing the ref.counter down to the real
* value of zero. This destroys the channel.
*/
Tcl_SpliceChannel(evPtr->chan);
Tcl_UnregisterChannel((Tcl_Interp *) NULL, evPtr->chan);
return 1;
}
/* Our caller (ThreadExitProc) will pass the channel back.
*/
return 1;
}
/*
* If it was NULL, we were in the middle of servicing the event
* and it should be removed
*/
return (eventPtr->proc == NULL);
}
/*
*----------------------------------------------------------------------
*
* ThreadExitProc --
*
* This is called when the thread exits.
*
* Results:
* None.
*
* Side effects:
* It unblocks anyone that is waiting on a send to this thread.
* It cleans up any events in the event queue for this thread.
*
*----------------------------------------------------------------------
*/
static void
ThreadExitProc(clientData)
ClientData clientData;
{
char *threadEvalScript = (char*)clientData;
const char *diemsg = "target thread died";
ThreadEventResult *resultPtr, *nextPtr;
Tcl_ThreadId self = Tcl_GetCurrentThread();
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
TransferResult *tResultPtr, *tNextPtr;
if (threadEvalScript && threadEvalScript != threadEmptyResult) {
ckfree((char*)threadEvalScript);
}
Tcl_MutexLock(&threadMutex);
/*
* NaviServer/AOLserver and threadpool threads get started/stopped
* out of the control of this interface so this is
* the first chance to split them out of the thread list.
*/
ListRemoveInner(tsdPtr);
/*
* Delete events posted to our queue while we were running.
* For threads exiting from the thread::wait command, this
* has already been done in ThreadWait() function.
* For one-shot threads, having something here is a very
* strange condition. It *may* happen if somebody posts us
* an event while we were in the middle of processing some
* lengthly user script. It is unlikely to happen, though.
*/
Tcl_DeleteEvents((Tcl_EventDeleteProc*)ThreadDeleteEvent, NULL);
/*
* Walk the list of threads waiting for result from us
* and inform them that we're about to exit.
*/
for (resultPtr = resultList; resultPtr; resultPtr = nextPtr) {
nextPtr = resultPtr->nextPtr;
if (resultPtr->srcThreadId == self) {
/*
* We are going away. By freeing up the result we signal
* to the other thread we don't care about the result.
*/
SpliceOut(resultPtr, resultList);
ckfree((char*)resultPtr);
} else if (resultPtr->dstThreadId == self) {
/*
* Dang. The target is going away. Unblock the caller.
* The result string must be dynamically allocated
* because the main thread is going to call free on it.
*/
resultPtr->result = strcpy(ckalloc(1+strlen(diemsg)), diemsg);
resultPtr->code = TCL_ERROR;
resultPtr->errorCode = resultPtr->errorInfo = NULL;
Tcl_ConditionNotify(&resultPtr->done);
}
}
for (tResultPtr = transferList; tResultPtr; tResultPtr = tNextPtr) {
tNextPtr = tResultPtr->nextPtr;
if (tResultPtr->srcThreadId == self) {
/*
* We are going away. By freeing up the result we signal
* to the other thread we don't care about the result.
*
* This should not happen, as this thread should be in
* ThreadTransfer at location (*).
*/
SpliceOut(tResultPtr, transferList);
ckfree((char*)tResultPtr);
} else if (tResultPtr->dstThreadId == self) {
/*
* Dang. The target is going away. Unblock the caller.
* The result string must be dynamically allocated
* because the main thread is going to call free on it.
*/
tResultPtr->resultMsg = strcpy(ckalloc(1+strlen(diemsg)),
diemsg);
tResultPtr->resultCode = TCL_ERROR;
Tcl_ConditionNotify(&tResultPtr->done);
}
}
Tcl_MutexUnlock(&threadMutex);
}
/*
*----------------------------------------------------------------------
*
* ThreadGetHandle --
*
* Construct the handle of the thread which is suitable
* to pass to Tcl.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
ThreadGetHandle(thrId, handlePtr)
Tcl_ThreadId thrId;
char *handlePtr;
{
sprintf(handlePtr, THREAD_HNDLPREFIX"%p", thrId);
}
/*
*----------------------------------------------------------------------
*
* ThreadGetId --
*
* Returns the ID of thread given it's Tcl handle.
*
* Results:
* Thread ID.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ThreadGetId(interp, handleObj, thrIdPtr)
Tcl_Interp *interp;
Tcl_Obj *handleObj;
Tcl_ThreadId *thrIdPtr;
{
const char *thrHandle = Tcl_GetString(handleObj);
if (sscanf(thrHandle, THREAD_HNDLPREFIX"%p", thrIdPtr) == 1) {
return TCL_OK;
}
Tcl_AppendResult(interp, "invalid thread handle \"",
thrHandle, "\"", NULL);
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* ErrorNoSuchThread --
*
* Convenience function to set interpreter result when the thread
* given by it's ID cannot be found.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
ErrorNoSuchThread(interp, thrId)
Tcl_Interp *interp;
Tcl_ThreadId thrId;
{
char thrHandle[THREAD_HNDLMAXLEN];
ThreadGetHandle(thrId, thrHandle);
Tcl_AppendResult(interp, "thread \"", thrHandle,
"\" does not exist", NULL);
}
/*
*----------------------------------------------------------------------
*
* ThreadCutChannel --
*
* Dissociate a Tcl channel from the current thread/interp.
*
* Results:
* None.
*
* Side effects:
* Events still pending in the thread event queue and ready to fire
* are not processed.
*
*----------------------------------------------------------------------
*/
static void
ThreadCutChannel(interp, chan)
Tcl_Interp *interp;
Tcl_Channel chan;
{
Tcl_DriverWatchProc *watchProc;
Tcl_ClearChannelHandlers(chan);
watchProc = Tcl_ChannelWatchProc(Tcl_GetChannelType(chan));
/*
* This effectively disables processing of pending
* events which are ready to fire for the given
* channel. If we do not do this, events will hit
* the detached channel which is potentially being
* owned by some other thread. This will wreck havoc
* on our memory and eventually badly hurt us...
*/
if (watchProc) {
(*watchProc)(Tcl_GetChannelInstanceData(chan), 0);
}
/*
* Artificially bump the channel reference count
* which protects us from channel being closed
* during the Tcl_UnregisterChannel().
*/
Tcl_RegisterChannel((Tcl_Interp *) NULL, chan);
Tcl_UnregisterChannel(interp, chan);
Tcl_CutChannel(chan);
}
/* EOF $RCSfile: threadCmd.c,v $ */
/* Emacs Setup Variables */
/* Local Variables: */
/* mode: C */
/* indent-tabs-mode: nil */
/* c-basic-offset: 4 */
/* End: */
|