File: Thread.pmod

package info (click to toggle)
pike8.0 8.0.1956-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 60,580 kB
  • sloc: ansic: 259,734; xml: 36,320; makefile: 3,748; sh: 1,713; cpp: 1,349; awk: 1,036; lisp: 655; javascript: 468; asm: 242; objc: 240; pascal: 157; sed: 34
file content (1296 lines) | stat: -rw-r--r-- 30,926 bytes parent folder | download | duplicates (3)
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
#pike __REAL_VERSION__

#if constant(thread_create)
constant Thread=__builtin.thread_id;

//! Create a new thread.
//!
//! @deprecated predef::Thread.Thread
optional __deprecated__ Thread `()( mixed f, mixed ... args )
{
  return thread_create( f, @args );
}

optional constant MutexKey=__builtin.mutex_key;
optional constant Mutex=__builtin.mutex;
optional constant Condition=__builtin.condition;
optional constant _Disabled=__builtin.threads_disabled;
optional constant Local=__builtin.thread_local;

optional constant thread_create = predef::thread_create;

optional constant this_thread = predef::this_thread;

optional constant all_threads = predef::all_threads;

constant THREAD_NOT_STARTED = __builtin.THREAD_NOT_STARTED;
constant THREAD_RUNNING = __builtin.THREAD_RUNNING;
constant THREAD_EXITED = __builtin.THREAD_EXITED;
constant THREAD_ABORTED = __builtin.THREAD_ABORTED;

private local void unlock(MutexKey key)
{
  // NB: Work-around in case the key has been used in a function call
  //     (the typical case being cond->wait()), and may have ended up
  //     in a backtrace to to eg the gc having executed a broken destroy().
  destruct(key);
}

//! @[Fifo] implements a fixed length first-in, first-out queue.
//! A fifo is a queue of values and is often used as a stream of data
//! between two threads.
//!
//! @seealso
//!   @[Queue]
//!
optional class Fifo {
  inherit Condition : r_cond;
  inherit Condition : w_cond;
  inherit Mutex : lock;
  
  array buffer;
  int ptr, num;
  int read_tres, write_tres;

  //! This function returns the number of elements currently in the fifo.
  //!
  //! @seealso
  //!   @[read()], @[write()]
  //!
  int size() {  return num; }

  protected final mixed read_unlocked()
  {
    mixed tmp=buffer[ptr];
    buffer[ptr++] = 0;	// Throw away any references.
    ptr%=sizeof(buffer);
    if(read_tres < sizeof(buffer))
    {
      if(num-- == read_tres)
	w_cond::broadcast();
    }else{
      num--;
      w_cond::broadcast();
    }
    return tmp;
  }

  //! This function retrieves a value from the fifo. Values will be
  //! returned in the order they were written. If there are no values
  //! present in the fifo the current thread will sleep until some other
  //! thread writes one.
  //!
  //! @seealso
  //!   @[try_read()], @[read_array()], @[write()]
  //!
  mixed read()
  {
    object key=lock::lock();
    while(!num) r_cond::wait(key);
    mixed res = read_unlocked();
    unlock(key);
    return res;
  }

  //! This function retrieves a value from the fifo if there is any
  //! there. Values will be returned in the order they were written.
  //! If there are no values present in the fifo then @[UNDEFINED]
  //! will be returned.
  //!
  //! @seealso
  //!   @[read()]
  //!
  mixed try_read()
  {
    if (!num) return UNDEFINED;
    object key=lock::lock();
    if (!num) return UNDEFINED;
    mixed res = read_unlocked();
    key = 0;
    return res;
  }

  protected final array read_all_unlocked()
  {
    array ret;

    switch (num) {
      case 0:
	ret = ({});
	break;

      case 1:
	ret=buffer[ptr..ptr];
	buffer[ptr++] = 0;	// Throw away any references.
	ptr%=sizeof(buffer);
	num = 0;
	w_cond::broadcast();
	break;

      default:
	if (ptr+num < sizeof(buffer)) {
	  ret = buffer[ptr..ptr+num-1];
	} else {
	  ret = buffer[ptr..]+buffer[..num-(sizeof(buffer)-ptr)-1];
	}
	ptr=num=0;
	buffer=allocate(sizeof(buffer)); // Throw away any references.
	w_cond::broadcast();
	break;
    }

    return ret;
  }

  //! This function returns all values in the fifo as an array. The
  //! values in the array will be in the order they were written. If
  //! there are no values present in the fifo the current thread will
  //! sleep until some other thread writes one.
  //!
  //! @seealso
  //!   @[read()], @[try_read_array()]
  //!
  array read_array()
  {
    object key=lock::lock();
    while(!num) r_cond::wait(key);
    array ret = read_all_unlocked();
    unlock(key);
    return ret;
  }

  //! This function returns all values in the fifo as an array but
  //! doesn't wait if there are no values there. The values in the
  //! array will be in the order they were written.
  //!
  //! @seealso
  //!   @[read_array()]
  //!
  array try_read_array()
  {
    if (!num) return ({});
    object key=lock::lock();
    array ret = read_all_unlocked();
    key = 0;
    return ret;
  }

  protected final void write_unlocked (mixed value)
  {
    buffer[(ptr + num) % sizeof(buffer)] = value;
    if(write_tres)
    {
      if(num++ == write_tres)
	r_cond::broadcast();
    }else{
      num++;
      r_cond::broadcast();
    }
  }

  //! Append a @[value] to the end of the fifo. If there is no more
  //! room in the fifo the current thread will sleep until space is
  //! available. The number of items in the queue after the write is
  //! returned.
  //!
  //! @seealso
  //!   @[read()]
  //!
  int write(mixed value)
  {
    object key=lock::lock();
    while(num == sizeof(buffer)) w_cond::wait(key);
    write_unlocked (value);
    int items = num;
    unlock(key);
    return items;
  }

  //! Append a @[value] to the end of the fifo. If there is no more
  //! room in the fifo then zero will be returned, otherwise the
  //! number of items in the fifo after the write is returned.
  //!
  //! @seealso
  //!   @[read()]
  //!
  int try_write(mixed value)
  {
    if (num == sizeof (buffer)) return 0;
    object key=lock::lock();
    if (num == sizeof (buffer)) return 0;
    write_unlocked (value);
    int items = num;
    key = 0;
    return items;
  }

  //! @decl void create()
  //! @decl void create(int size)
  //!
  //! Create a fifo. If the optional @[size] argument is present it
  //! sets how many values can be written to the fifo without blocking.
  //! The default @[size] is 128.
  //!
  protected void create(int|void size)
  {
    write_tres=0;
    buffer=allocate(read_tres=size || 128);
  }

  protected string _sprintf( int f )
  {
    if (!this)				// Only if not destructed
      return "(destructed)";
    return f=='O' && sprintf( "%O(%d / %d)", this_program,
			      size(), read_tres );
  }
}

//! @[Queue] implements a queue, or a pipeline. The main difference
//! between @[Queue] and @[Fifo] is that @[Queue]
//! will never block in write(), only allocate more memory.
//!
//! @fixme
//!   Ought to be made API-compatible with @[ADT.Queue].
//!
//! @seealso
//!   @[Fifo], @[ADT.Queue]
//!
optional class Queue {
  inherit Condition : r_cond;
  inherit Mutex : lock;
  
  array buffer=allocate(16);
  int r_ptr, w_ptr;
  
  //! This function returns the number of elements currently in the queue.
  //!
  //! @seealso
  //!   @[read()], @[write()]
  //!
  int size() {  return w_ptr - r_ptr;  }

  //! This function retrieves a value from the queue. Values will be
  //! returned in the order they were written. If there are no values
  //! present in the queue the current thread will sleep until some other
  //! thread writes one.
  //!
  //! @seealso
  //!   @[try_read()], @[write()]
  //!
  mixed read()
  {
    mixed tmp;
    object key=lock::lock();
    while(w_ptr == r_ptr) r_cond::wait(key);
    tmp=buffer[r_ptr];
    buffer[r_ptr++] = 0;	// Throw away any references.
    unlock(key);
    return tmp;
  }

  //! This function retrieves a value from the queue if there is any
  //! there. Values will be returned in the order they were written.
  //! If there are no values present in the fifo then @[UNDEFINED]
  //! will be returned.
  //!
  //! @seealso
  //!   @[write()]
  //!
  mixed try_read()
  {
    if (w_ptr == r_ptr) return UNDEFINED;
    object key=lock::lock();
    if (w_ptr == r_ptr) return UNDEFINED;
    mixed tmp=buffer[r_ptr];
    buffer[r_ptr++] = 0;	// Throw away any references.
    key=0;
    return tmp;
  }

  protected final array read_all_unlocked()
  {
    array ret;

    switch (w_ptr - r_ptr) {
      case 0:
	ret = ({});
	break;

      case 1:
	ret=buffer[r_ptr..r_ptr];
	buffer[r_ptr++] = 0;	// Throw away any references.
	break;

      default:
	ret = buffer[r_ptr..w_ptr-1];
	r_ptr = w_ptr = 0;
	buffer=allocate(sizeof(buffer)); // Throw away any references.
	break;
    }

    return ret;
  }

  //! This function returns all values in the queue as an array. The
  //! values in the array will be in the order they were written. If
  //! there are no values present in the queue the current thread will
  //! sleep until some other thread writes one.
  //!
  //! @seealso
  //!   @[read()], @[try_read_array()]
  //!
  array read_array()
  {
    object key=lock::lock();
    while (w_ptr == r_ptr) r_cond::wait(key);
    array ret = read_all_unlocked();
    unlock(key);
    return ret;
  }

  //! This function returns all values in the queue as an array but
  //! doesn't wait if there are no values there. The values in the
  //! array will be in the order they were written.
  //!
  //! @seealso
  //!   @[read_array()]
  //!
  array try_read_array()
  {
    if (w_ptr == r_ptr) return ({});
    object key=lock::lock();
    array ret = read_all_unlocked();
    key = 0;
    return ret;
  }

  //! Returns a snapshot of all the values in the queue, in the order
  //! they were written. The values are still left in the queue, so if
  //! other threads are reading from it, the returned value should be
  //! considered stale already on return.
  array peek_array()
  {
    if (w_ptr == r_ptr) return ({});
    MutexKey key = lock::lock();
    array ret = buffer[r_ptr..w_ptr - 1];
    key = 0;
    return ret;
  }

  //! This function puts a @[value] last in the queue. If the queue is
  //! too small to hold the @[value] it will be expanded to make room.
  //! The number of items in the queue after the write is returned.
  //!
  //! @seealso
  //!   @[read()]
  //!
  int write(mixed value)
  {
    object key=lock::lock();
    if(w_ptr >= sizeof(buffer))
    {
      buffer=buffer[r_ptr..];
      buffer+=allocate(sizeof(buffer)+1);
      w_ptr-=r_ptr;
      r_ptr=0;
    }
    buffer[w_ptr] = value;
    w_ptr++;
    int items = w_ptr - r_ptr;
    // NB: The mutex MUST be released before the broadcast to work
    //     around bugs in glibc 2.24 and earlier. This seems to
    //     affect eg RHEL 7 (glibc 2.17).
    //     cf https://sourceware.org/bugzilla/show_bug.cgi?id=13165
    key=0;
    r_cond::broadcast();
    return items;
  }

  protected string _sprintf( int f )
  {
    if (!this)				// Only if not destructed
      return "(destructed)";
    return f=='O' && sprintf( "%O(%d)", this_program, size() );
  }
}


//! A thread farm.
optional class Farm
{
  protected Mutex mutex = Mutex();
  protected Condition ft_cond = Condition();
  protected Queue job_queue = Queue();
  protected object dispatcher_thread;
  protected function(object, string:void) thread_name_cb;
  protected string thread_name_prefix;

  //! An asynchronous result.
  class Result
  {
    int ready;
    mixed value;
    function done_cb;

    //! @returns
    //!   @int
    //!     @value 1
    //!       Returns @expr{1@} when the result is available.
    //!     @value 0
    //!       Returns @expr{0@} (zero) when the result hasn't
    //!       arrived yet.
    //!     @value -1
    //!       Returns negative on failure.
    //!   @endint
    int status()
    {
      return ready;
    }

    //! @returns
    //!   Returns the result if available, a backtrace on failure,
    //!   and @expr{0@} (zero) otherwise.
    mixed result()
    {
      return value;
    }

    //! Wait for completion.
    mixed `()()
    {
      object key = mutex->lock();
      while(!ready)     ft_cond->wait(key);
      unlock(key);
      if( ready < 0 )   throw( value );
      return value;
    }

    //! Register a callback to be called when
    //! the result is available.
    //!
    //! @param to
    //!   Callback to be called. The first
    //!   argument to the callback will be
    //!   the result or the failure backtrace,
    //!   and the second @expr{0@} (zero) on
    //!   success, and @expr{1@} on failure.
    void set_done_cb( function to )
    {
      if( ready )
        to( value, ready<0 );
      else
        done_cb = to;
    }

    //! Register a failure.
    //!
    //! @param what
    //!   The corresponding backtrace.
    void provide_error( mixed what )
    {
      value = what;
      ready = -1;
      if( done_cb )
        done_cb( what, 1 );
    }

    //! Register a completed result.
    //!
    //! @param what
    //!   The result to register.
    void provide( mixed what )
    {
      ready = 1;
      value = what;
      if( done_cb )
        done_cb( what, 0 );
    }


    protected string _sprintf( int f )
    {
      if (!this)				// Only if not destructed
        return "(destructed)";
      switch( f )
      {
	case 't':
	  return "Thread.Farm().Result";
	case 'O':
	  return sprintf( "%t(%d %O)", this, ready, value );
      }
    }
  }

  //! A worker thread.
  protected class Handler
  {
    Mutex job_mutex = Mutex();
    Condition cond = Condition();
    array(object|array(function|array)) job;
    object thread;

    float total_time;
    int handled, max_time;

    protected int ready;

    void update_thread_name(int is_exiting)
    {
      if (thread_name_cb) {
        string th_name =
          !is_exiting &&
          sprintf("%s Handler 0x%x", thread_name_prefix, thread->id_number());
        thread_name_cb(thread, th_name);
      }
    }

    void handler()
    {
      array(object|array(function|array)) q;
      object key = job_mutex->lock();
      ready = 1;
      while( 1 )
      {
        cond->wait(key);
        if( q = job )
        {
          mixed res, err;
          int st = gethrtime();

          err = catch(res = q[1][0]( @q[1][1] ));

          if( q[0] )
          {
            if( err )
              ([object]q[0])->provide_error( err );
            else
              ([object]q[0])->provide( res );
          }
          object lock = mutex->lock();
          free_threads += ({ this });
          lock = 0;
          st = gethrtime()-st;
          total_time += st/1000.0;
          handled++;
          job = 0;
          q = 0;
          if( st > max_time )
            max_time = st;
          ft_cond->broadcast();
        } else {
          object lock = mutex->lock();
          threads -= ({ this });
          free_threads -= ({ this });
          lock = 0;
          update_thread_name(1);
	  unlock(key);
          destruct();
          return;
        }
      }
    }

    void run( array(function|array) what, object|void resobj )
    {
      while(!ready) sleep(0.1);
      object key = job_mutex->lock();
      job = ({ resobj, what });
      cond->signal();
      key = 0;
    }

    //! Get some statistics about the worker thread.
    string debug_status()
    {
      return ("Thread:\n"
              " Handled works: "+handled+"\n"+
              (handled?
               " Average time:  "+((int)(total_time / handled))+"ms\n"
               " Max time:      "+sprintf("%2.2fms\n", max_time/1000.0):"")+
              " Status:        "+(job?"Working":"Idle" )+"\n"+
              (job?
               ("    "+
                replace( describe_backtrace(thread->backtrace()),
                         "\n",
                         "\n    ")):"")
              +"\n\n");
    }

    protected void create()
    {
      thread = thread_create( handler );
      update_thread_name(0);
    }


    protected string _sprintf( int f )
    {
      if (!this)				// Only if not destructed
        return "(destructed)";
      switch( f )
      {
	case 't':
	  return "Thread.Farm().Handler";
	case 'O':
	  return sprintf( "%t(%f / %d,  %d)", this,
			  total_time, max_time, handled );
      }
    }
  }

  protected array(Handler) threads = ({});
  protected array(Handler) free_threads = ({});
  protected int max_num_threads = 20;

  protected Handler aquire_thread()
  {
    object lock = mutex->lock();
    while( !sizeof(free_threads) )
    {
      if( sizeof(threads) < max_num_threads )
      {
        threads += ({ Handler() });
        free_threads += ({ threads[-1] });
      } else {
        ft_cond->wait(lock);
      }
    }
    object(Handler) t = free_threads[0];
    free_threads = free_threads[1..];
    unlock(lock);
    return t;
  }
        

  protected void dispatcher()
  {
    while( array q = [array]job_queue->read() ) {
      aquire_thread()->run( q[1], q[0] );
      q = 0;
    }
    if (thread_name_cb)
      thread_name_cb(this_thread(), 0);
  }

  protected class ValueAdjuster( object r, object r2, int i, mapping v )
  {
    void go(mixed vn, int err)
    {
      if (!r->status()) {
	([array]r->value)[ i ] = vn;
	if( err )
	  r->provide_error( err );
	if( !--v->num_left )
	  r->provide( r->value );
      }
      destruct();
    }
  }


  //! Register multiple jobs.
  //!
  //! @param fun_args
  //!   An array of arrays where the first element
  //!   is a function to call, and the second is
  //!   a corresponding array of arguments.
  //!
  //! @returns
  //!   Returns a @[Result] object with an array
  //!   with one element for the result for each
  //!   of the functions in @[fun_args].
  //!
  //! @note
  //!   Do not modify the elements of @[fun_args]
  //!   before the result is available.
  //!
  //! @note
  //!   If any of the functions in @[fun_args] throws
  //!   and error, all of the accumulated results
  //!   (if any) will be dropped from the result, and
  //!   the first backtrace be provided.
  //!
  //! @seealso
  //!   @[run_multiple_async()]
  Result run_multiple( array(array(function|array)) fun_args )
  {
    Result r = Result(); // private result..
    r->value = allocate( sizeof( fun_args ) );
    mapping nl = ([ "num_left":sizeof( fun_args ) ]);
    for( int i=0; i<sizeof( fun_args ); i++ )
    {
      Result r2 = Result();
      r2->set_done_cb( ValueAdjuster( r, r2, i, nl )->go );
      job_queue->write( ({ r2, fun_args[i] }) );
    }
    return r;
  }


  //! Register multiple jobs where the return values
  //! are to be ignored.
  //!
  //! @param fun_args
  //!   An array of arrays where the first element
  //!   is a function to call, and the second is
  //!   a corresponding array of arguments.
  //!
  //! @note
  //!   Do not modify the elements of @[fun_args]
  //!   before the result is available.
  //!
  //! @seealso
  //!   @[run_multiple()]
  void run_multiple_async( array fun_args )
  {
    for( int i=0; i<sizeof( fun_args ); i++ )
      job_queue->write( ({ 0, fun_args[i] }) );
  }


  //! Register a job for the thread farm.
  //!
  //! @param f
  //!   Function to call with @@@[args] to
  //!   perform the job.
  //!
  //! @param args
  //!   The parameters for @[f].
  //!
  //! @returns
  //!   Returns a @[Result] object for the job.
  //!
  //! @note
  //!   In Pike 7.8 and earlier this function
  //!   was broken and returned a @[Result]
  //!   object that wasn't connected to the job.
  //!
  //! @seealso
  //!   @[run_async()]
  Result run( function f, mixed ... args )
  {
    Result ro = Result();
    job_queue->write( ({ ro, ({f, args }) }) );
    return ro;
  }

  //! Register a job for the thread farm
  //! where the return value from @[f] is
  //! ignored.
  //!
  //! @param f
  //!   Function to call with @@@[args] to
  //!   perform the job.
  //!
  //! @param args
  //!   The parameters for @[f].
  //!
  //! @seealso
  //!   @[run()]
  void run_async( function f, mixed ... args )
  {
    job_queue->write( ({ 0, ({f, args }) }) );
  }

  //! Set the maximum number of worker threads
  //! that the thread farm may have.
  //!
  //! @param to
  //!   The new maximum number.
  //!
  //! If there are more worker threads than @[to],
  //! the function will wait until enough threads
  //! have finished, so that the total is @[to] or less.
  //!
  //! The default maximum number of worker threads is @expr{20@}.
  int set_max_num_threads( int(1..) to )
  {
    int omnt = max_num_threads;
    if( to <= 0 )
      error("Illegal argument 1 to set_max_num_threads,"
            "num_threads must be > 0\n");

    max_num_threads = to;
    while( sizeof( threads ) > max_num_threads )
    {
      object key = mutex->lock();
      while( sizeof( free_threads ) )
        free_threads[0]->cond->signal();
      if( sizeof( threads ) > max_num_threads)
        ft_cond->wait(key);
      unlock(key);
    }
    ft_cond->broadcast( );
    return omnt;
  }

  //! Provide a callback function to track names of threads created by the
  //! farm.
  //!
  //! @param cb
  //!   The callback function. This will get invoked with the thread as the
  //!   first parameter and the name as the second whenever a thread is
  //!   created. When the same thread terminates the callback is invoked
  //!   again with @[0] as the second parameter. Set @[cb] to @[0] to stop
  //!   any previously registered callbacks from being called.
  //!
  //! @param prefix
  //!   An optional name prefix to distinguish different farms. If not given
  //!   a prefix will be generated automatically.
  void set_thread_name_cb(function(object, string:void) cb, void|string prefix)
  {
    thread_name_cb = cb;
    thread_name_prefix =
      cb &&
      (prefix || sprintf("Thread.Farm 0x%x", dispatcher_thread->id_number()));

    //  Give a name to all existing threads
    if (thread_name_cb) {
      thread_name_cb(dispatcher_thread, thread_name_prefix + " Dispatcher");
      foreach (threads, Handler t)
        t->update_thread_name(0);
    }
  }

  //! Get some statistics for the thread farm.
  string debug_status()
  {
    string res = sprintf("Thread farm\n"
                         "  Max threads     = %d\n"
                         "  Current threads = %d\n"
                         "  Working threads = %d\n"
                         "  Jobs in queue   = %d\n\n",
                         max_num_threads, sizeof(threads), 
                         (sizeof(threads)-sizeof(free_threads)),
                         job_queue->size() );
    
    foreach( threads, Handler t )
      res += t->debug_status();
    return res;
  }

  protected string _sprintf( int f )
  {
    if (!this)				// Only if not destructed
      return "(destructed)";
    return f=='O' && sprintf( "%O(/* %s */)", this_program, debug_status() );
  }

  protected void create()
  {
    dispatcher_thread = thread_create( dispatcher );
  }
}

//! When this key is destroyed, the corresponding resource counter
//! will be decremented.
//!
//! @seealso
//!   @[ResourceCount], @[MutexKey]
//!
optional class ResourceCountKey {
#if constant(Pike.DestructImmediate)
  private inherit Pike.DestructImmediate;
#endif

  /*semi*/private ResourceCount parent;

  /*semi*/private void create(ResourceCount _parent) {
    parent = _parent;
  }

  /*semi*/private void destroy() {
    MutexKey key = parent->_mutex->lock();
    --parent->_count;
    parent->_cond->signal();
  }
}

//! Implements an inverted-semaphore-like resource
//! counter.  A thread can poll or perform a blocking wait for the
//! resource-count to drop below a certain @ref{level@}.
//!
//! @seealso
//!   @[ResourceCountKey], @[Condition], @[Mutex]
optional class ResourceCount {
  /*semi*/final int _count;
  /*semi*/final Condition _cond = Condition();
  /*semi*/final Mutex _mutex = Mutex();

  //! @param level
  //!   The maximum level that is considered drained.
  //!
  //! @returns
  //!   True if the resource counter drops to equal or below @ref{level@}.
  /*semi*/final int(0..1) drained(void|int level) {
    return level >= _count;
  }

  //! Blocks until the resource-counter dips to max @ref{level@}.
  //!
  //! @param level
  //!   The maximum level that is considered drained.
  /*semi*/final void wait_till_drained(void|int level) {
    MutexKey key = _mutex->lock();
    while (_count > level)		// Recheck before allowing further
      _cond->wait(key);
    unlock(key);
  }

  //! Increments the resource-counter.
  //! @returns
  //!   A @[ResourceCountKey] to decrement the resource-counter again.
  /*semi*/final ResourceCountKey acquire() {
    MutexKey key = _mutex->lock();
    _count++;
    return ResourceCountKey(this);
  }

  /*semi*/private string _sprintf(int type) {
    string res = UNDEFINED;
    if (!this)				// Only if not destructed
      return "(destructed)";
    switch(type) {
      case 'O':
        res = sprintf("Count: %d", _count);
        break;
      case 'd':
        res = sprintf("%d", _count);
        break;
    }
    return res;
  }
}

#else /* !constant(thread_create) */

// Simulations of some of the classes for nonthreaded use.

/* Fallback implementation of Thread.Local */
optional class Local
{
  protected mixed data;
  mixed get() {return data;}
  mixed set (mixed val) {return data = val;}
}

/* Fallback implementation of Thread.MutexKey */
optional class MutexKey (protected function(:void) dec_locks)
{
  inherit Builtin.DestructImmediate;

  int `!()
  {
    // Should be destructed when the mutex is, but we can't pull that
    // off. Try to simulate it as well as possible.
    if (dec_locks) return 0;
    destruct (this);
    return 1;
  }

  protected void destroy()
  {
    if (dec_locks) dec_locks();
  }
}

/* Fallback implementation of Thread.Mutex */
optional class Mutex
{
  protected int locks = 0;
  protected void dec_locks() {locks--;}

  MutexKey lock (int|void type)
  {
    switch (type) {
      default:
	error ("Unknown mutex locking style: %d\n", type);
      case 0:
	if (locks) error ("Recursive mutex locks.\n");
	break;
      case 1:
	if (locks)
	  // To be really accurate we should hang now, but somehow
	  // that doesn't seem too useful.
	  error ("Deadlock detected.\n");
	break;
      case 2:
	if (locks) return 0;
    }
    locks++;
    return MutexKey (dec_locks);
  }

  MutexKey trylock (int|void type)
  {
    switch (type) {
      default:
	error ("Unknown mutex locking style: %d\n", type);
      case 0:
	if (locks) error ("Recursive mutex locks.\n");
	break;
      case 1:
      case 2:
    }
    if (locks) return 0;
    locks++;
    return MutexKey (dec_locks);
  }

  Condition condition ()
  {
    return Condition(this);
  }
}

// Fallback implementation of Thread.Condition.
class Condition (protected Mutex|void mutex)
{
  variant void wait(MutexKey key, void|int|float seconds)
  {
    if (!seconds || seconds == 0.0) {
      // To be really accurate we should hang now, but somehow
      // that doesn't seem too useful.
      error ("Deadlock detected.\n");
    }
    sleep(seconds);
  }

  variant void wait(MutexKey key, int seconds, int nanos)
  {
    wait(key, seconds + nanos*1e-9);
  }

  void signal()
  {
  }

  void broadcast()
  {
  }
}

// Fallback implementation of Thread.Fifo.
optional class Fifo
{
  array buffer;
  int ptr, num;
  int read_tres, write_tres;

  int size() {  return num; }

  mixed read()
  {
    if (!num) error ("Deadlock detected - fifo empty.\n");
    return try_read();
  }

  mixed try_read()
  {
    if (!num) return UNDEFINED;
    mixed tmp=buffer[ptr];
    buffer[ptr++] = 0;	// Throw away any references.
    ptr%=sizeof(buffer);
    return tmp;
  }

  array read_array()
  {
    if (!num) error ("Deadlock detected - fifo empty.\n");
    return try_read_array();
  }

  array try_read_array()
  {
    array ret;
    switch (num) {
      case 0:
	ret = ({});
	break;

      case 1:
	ret=buffer[ptr..ptr];
	buffer[ptr++] = 0;	// Throw away any references.
	ptr%=sizeof(buffer);
	num = 0;
	break;

      default:
	if (ptr+num < sizeof(buffer)) {
	  ret = buffer[ptr..ptr+num-1];
	} else {
	  ret = buffer[ptr..]+buffer[..num-(sizeof(buffer)-ptr)-1];
	}
	ptr=num=0;
	buffer=allocate(sizeof(buffer)); // Throw away any references.
	break;
    }

    return ret;
  }

  int try_write(mixed value)
  {
    if (num == sizeof (buffer)) return 0;
    buffer[(ptr + num) % sizeof(buffer)] = value;
    return ++num;
  }

  int write(mixed value)
  {
    if (!try_write(value)) error("Deadlock detected - fifo full.\n");
    return num;
  }

  protected void create(int|void size)
  {
    write_tres=0;
    buffer=allocate(read_tres=size || 128);
  }

  protected string _sprintf( int f )
  {
    if (!this)				// Only if not destructed
      return "(destructed)";
    return f=='O' && sprintf( "%O(%d / %d)", this_program,
			      size(), read_tres );
  }
}

// Fallback implementation of Thread.Queue.
optional class Queue
{
  array buffer=allocate(16);
  int r_ptr, w_ptr;
  
  int size() {  return w_ptr - r_ptr;  }

  mixed read()
  {
    if (w_ptr == r_ptr) error ("Deadlock detected - queue empty.\n");
    return try_read();
  }

  mixed try_read()
  {
    if (w_ptr == r_ptr) return UNDEFINED;
    mixed tmp=buffer[r_ptr];
    buffer[r_ptr++] = 0;	// Throw away any references.
    return tmp;
  }

  array read_array()
  {
    if (w_ptr == r_ptr) error ("Deadlock detected - queue empty.\n");
    return try_read_array();
  }

  array try_read_array()
  {
    array ret;

    switch (w_ptr - r_ptr) {
      case 0:
	ret = ({});
	break;

      case 1:
	ret=buffer[r_ptr..r_ptr];
	buffer[r_ptr++] = 0;	// Throw away any references.
	break;

      default:
	ret = buffer[r_ptr..w_ptr-1];
	r_ptr = w_ptr = 0;
	buffer=allocate(sizeof(buffer)); // Throw away any references.
	break;
    }

    return ret;
  }

  array peek_array()
  {
    return buffer[r_ptr..w_ptr-1];
  }

  int write(mixed value)
  {
    if(w_ptr >= sizeof(buffer))
    {
      buffer=buffer[r_ptr..];
      buffer+=allocate(sizeof(buffer)+1);
      w_ptr-=r_ptr;
      r_ptr=0;
    }
    buffer[w_ptr] = value;
    w_ptr++;
    return w_ptr - r_ptr;
  }

  protected string _sprintf( int f )
  {
    if (!this)				// Only if not destructed
      return "(destructed)";
    return f=='O' && sprintf( "%O(%d)", this_program, size() );
  }
}

// Fallback implementation of Thread.ResourceCountKey.
class ResourceCountKey {

  private inherit __builtin.DestructImmediate;

  /*semi*/private ResourceCount parent;

  protected void create(ResourceCount _parent)
  {
    parent = _parent;
  }

  protected void destroy()
  {
    --parent->_count;
  }
}

// Fallback implementation of Thread.ResourceCount.
class ResourceCount {
  /*semi*/final int _count;

  /*semi*/final int(0..1) drained(void|int level) {
    return level >= _count;
  }

  /*semi*/final void wait_till_drained(void|int level) {
    if (_count > level) {
      // To be really accurate we should hang now, but somehow
      // that doesn't seem too useful.
      error ("Deadlock detected.\n");
    }
  }

  /*semi*/final ResourceCountKey acquire() {
    _count++;
    return ResourceCountKey(this);
  }

  protected string _sprintf(int type)
  {
    string res = UNDEFINED;
    if (!this)				// Only if not destructed
      return "(destructed)";
    switch(type) {
      case 'O':
        res = sprintf("Count: %d", _count);
        break;
      case 'd':
        res = sprintf("%d", _count);
        break;
    }
    return res;
  }
}

#endif /* !constant(thread_create) */