This repository was archived by the owner on Feb 13, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathstacklessmodule.c
More file actions
1762 lines (1544 loc) · 53.6 KB
/
Copy pathstacklessmodule.c
File metadata and controls
1762 lines (1544 loc) · 53.6 KB
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
/* Stackless module implementation */
#include "Python.h"
#include "pythread.h"
#ifdef STACKLESS
#include "pycore_stackless.h"
#define IMPLEMENT_STACKLESSMODULE
#include "pycore_slp_prickelpit.h"
#include <stddef.h> /* for offsetof() */
/*[clinic input]
module _stackless
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9edda6c2b9dbd340]*/
#include "clinic/stacklessmodule.c.h"
/******************************************************
The atomic context manager
This is provided here for perfomance, because setting
the atomic state is an important part of writing higher
level operations. It is equivalent to the following,
but much faster:
@contextlib.contextmanager
def atomic():
old = stackless.getcurrent().set_atomic(True)
try:
yield
finally:
stackless.getcurrent().set_atomic(old)
******************************************************/
typedef struct PyAtomicObject
{
PyObject_HEAD
int old;
} PyAtomicObject;
static PyObject *
atomic_enter(PyObject *self, PyObject *unused)
{
PyAtomicObject *a = (PyAtomicObject*)self;
PyObject *c = PyStackless_GetCurrent();
if (c) {
a->old = PyTasklet_GetAtomic((PyTaskletObject*)c);
PyTasklet_SetAtomic((PyTaskletObject*)c, 1);
Py_DECREF(c);
}
Py_RETURN_NONE;
}
static PyObject *
atomic_exit(PyObject *self, PyObject *args)
{
PyAtomicObject *a = (PyAtomicObject*)self;
PyObject *c = PyStackless_GetCurrent();
if (c) {
PyTasklet_SetAtomic((PyTaskletObject*)c, a->old);
Py_DECREF(c);
}
Py_RETURN_NONE;
}
static PyMethodDef atomic_methods[] = {
{"__enter__", (PyCFunction)atomic_enter, METH_NOARGS, NULL},
{"__exit__", (PyCFunction)atomic_exit, METH_VARARGS, NULL},
{NULL, NULL}
};
PyDoc_STRVAR(PyAtomic_Type__doc__,
"A context manager for setting the 'atomic' flag of the \n\
current tasklet to true for the duration.\n");
PyTypeObject PyAtomic_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "_stackless.atomic",
.tp_basicsize = sizeof(PyAtomicObject),
.tp_getattro = PyObject_GenericGetAttr,
.tp_setattro = PyObject_GenericSetAttr,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = PyAtomic_Type__doc__,
.tp_methods = atomic_methods,
.tp_new = PyType_GenericNew
};
/******************************************************
The Stackless Module
******************************************************/
/*
* pickle flags
*/
/*[clinic input]
_stackless.pickle_flags_default
new_default: 'l' = -1
The new default value for pickle-flags.
mask: 'l' = -1
A bit mask, that indicates the valid bits in argument "new_default".
Get and set the per interpreter default value for pickle-flags.
The function returns the previous pickle-flags. To inquire the pickle-flags
without changing them, omit the arguments.
[clinic start generated code]*/
static PyObject *
_stackless_pickle_flags_default_impl(PyObject *module, long new_default,
long mask)
/*[clinic end generated code: output=60e5303388b2dee1 input=ed5fcb139f236812]*/
{
PyThreadState *ts = _PyThreadState_GET();
long old_default;
if (new_default < -1 || (new_default & mask) > SLP_PICKLEFLAGS__MAX_VALUE) {
PyErr_SetString(PyExc_ValueError, "you must not set an undefined pickle-flag");
return NULL;
}
old_default = ts->interp->st.pickleflags;
if (new_default != -1) {
uint8_t v;
Py_BUILD_ASSERT(sizeof(ts->interp->st.pickleflags) == sizeof(v));
v = ts->interp->st.pickleflags & ~mask;
new_default &= mask;
v |= Py_SAFE_DOWNCAST(new_default, long, uint8_t);
ts->interp->st.pickleflags = Py_SAFE_DOWNCAST(v, long, uint8_t);
}
return PyLong_FromLong(old_default);
}
/*[clinic input]
_stackless.pickle_flags
new_flags: 'l' = -1
The new value for pickle-flags of the current thread.
mask: 'l' = -1
A bit mask, that indicates the valid bits in argument "new_flags".
Get and set pickle-flags.
A number of option flags control various aspects of Stackless pickling
behavior. The flags are represented by the bits of an integer value.
The function returns the previous pickle-flags. To inquire the
pickle-flags without changing them, omit the arguments.
Currently the following bits are defined:
- bit 0, value 1: pickle the tracing/profiling state of a tasklet;
- bit 1, value 2: preserve the finalizer of an asynchronous generator;
- bit 2, value 4: reset the finalizer of an asynchronous generator.
All other bits must be set to 0.
[clinic start generated code]*/
static PyObject *
_stackless_pickle_flags_impl(PyObject *module, long new_flags, long mask)
/*[clinic end generated code: output=fd773a5b06ab0c48 input=36479a8e5486c711]*/
{
PyThreadState *ts = _PyThreadState_GET();
long old_flags;
Py_BUILD_ASSERT(sizeof(ts->interp->st.pickleflags) == sizeof(ts->st.pickleflags));
Py_BUILD_ASSERT((1U << (sizeof(ts->st.pickleflags) * CHAR_BIT)) > SLP_PICKLEFLAGS__MAX_VALUE);
if (new_flags < -1 || (new_flags & mask) > SLP_PICKLEFLAGS__MAX_VALUE) {
PyErr_SetString(PyExc_ValueError, "you must not set an undefined pickle-flag");
return NULL;
}
old_flags = ts->st.pickleflags;
if (new_flags != -1) {
uint8_t v;
Py_BUILD_ASSERT(sizeof(ts->st.pickleflags) == sizeof(v));
v = ts->st.pickleflags & ~mask;
new_flags &= mask;
v |= Py_SAFE_DOWNCAST(new_flags, long, uint8_t);
ts->st.pickleflags = Py_SAFE_DOWNCAST(v, long, uint8_t);
}
return PyLong_FromLong(old_flags);
}
PyDoc_STRVAR(schedule__doc__,
"schedule(retval=stackless.current) -- switch to the next runnable tasklet.\n\
The return value for this call is retval, with the current\n\
tasklet as default.\n\
schedule_remove(retval=stackless.current) -- ditto, and remove self.");
static PyObject *
schedule(PyObject *self, PyObject *args, PyObject *kwds);
static PyObject *
schedule_remove(PyObject *self, PyObject *args, PyObject *kwds);
static PyObject *
PyStackless_Schedule_M(PyObject *retval, int remove)
{
PyMethodDef sched = {"schedule", (PyCFunction)(void(*)(void))schedule, METH_VARARGS|METH_KEYWORDS};
PyMethodDef s_rem = {"schedule", (PyCFunction)(void(*)(void))schedule_remove, METH_VARARGS|METH_KEYWORDS};
if (remove)
return PyStackless_CallCMethod_Main(&s_rem, NULL, "O", retval);
else
return PyStackless_CallCMethod_Main(&sched, NULL, "O", retval);
}
PyObject *
PyStackless_Schedule(PyObject *retval, int remove)
{
STACKLESS_GETARG();
PyThreadState *ts = _PyThreadState_GET();
PyTaskletObject *prev = ts->st.current, *next;
PyObject *tmpval, *ret = NULL;
int switched, fail;
if (ts->st.main == NULL)
return PyStackless_Schedule_M(retval, remove);
assert(prev);
next = prev->next;
/* make sure we hold a reference to the previous tasklet.
* this will be decrefed after the switch is complete
*/
Py_INCREF(prev);
assert(ts->st.del_post_switch == NULL);
ts->st.del_post_switch = (PyObject*)prev;
TASKLET_CLAIMVAL(prev, &tmpval);
TASKLET_SETVAL(prev, retval);
if (remove) {
slp_current_remove();
Py_DECREF(prev);
if (next == prev)
next = 0; /* we were the last runnable tasklet */
}
fail = slp_schedule_task(&ret, prev, next, stackless, &switched);
if (fail) {
TASKLET_SETVAL_OWN(prev, tmpval);
if (remove) {
slp_current_unremove(prev);
Py_INCREF(prev);
}
} else
Py_DECREF(tmpval);
if (!switched || fail)
/* we must do this ourselves */
Py_CLEAR(ts->st.del_post_switch);
return ret;
}
PyObject *
PyStackless_Schedule_nr(PyObject *retval, int remove)
{
PyThreadState *ts = _PyThreadState_GET();
STACKLESS_PROPOSE_ALL(ts);
return PyStackless_Schedule(retval, remove);
}
static PyObject *
schedule(PyObject *self, PyObject *args, PyObject *kwds)
{
STACKLESS_GETARG();
PyObject *retval = (PyObject *) _PyThreadState_GET()->st.current;
static char *argnames[] = {"retval", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:schedule",
argnames, &retval))
{
return NULL;
}
STACKLESS_PROMOTE_ALL();
return PyStackless_Schedule(retval, 0);
}
static PyObject *
schedule_remove(PyObject *self, PyObject *args, PyObject *kwds)
{
STACKLESS_GETARG();
PyObject *retval = (PyObject *) _PyThreadState_GET()->st.current;
static char *argnames[] = {"retval", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:schedule_remove",
argnames, &retval))
{
return NULL;
}
STACKLESS_PROMOTE_ALL();
return PyStackless_Schedule(retval, 1);
}
PyDoc_STRVAR(getruncount__doc__,
"getruncount() -- return the number of runnable tasklets.");
int
PyStackless_GetRunCount(void)
{
PyThreadState *ts = _PyThreadState_GET();
return ts->st.runcount;
}
static PyObject *
getruncount(PyObject *self, PyObject *unused)
{
PyThreadState *ts = _PyThreadState_GET();
return PyLong_FromLong(ts->st.runcount);
}
PyDoc_STRVAR(getcurrent__doc__,
"getcurrent() -- return the currently executing tasklet.");
PyObject *
PyStackless_GetCurrent(void)
{
PyThreadState *ts = _PyThreadState_GET();
/* only if there is a main tasklet, is the current one
* the active one. Otherwise, it is merely a runnable
* tasklet
*/
PyObject *t = NULL;
if (ts->st.main)
t = (PyObject*)ts->st.current;
Py_XINCREF(t); /* CCP change, allow to work if stackless isn't init */
return t;
}
static PyObject *
getcurrent(PyObject *self, PyObject *unused)
{
return PyStackless_GetCurrent();
}
PyDoc_STRVAR(getcurrentid__doc__,
"getcurrentid() -- return the id of the currently executing tasklet.");
unsigned long
PyStackless_GetCurrentId(void)
{
PyThreadState *ts = PyGILState_GetThisThreadState();
PyTaskletObject *t = NULL;
/* if there is threadstate, and there is a main tasklet, then the
* "current" is the actively running tasklet.
* If there isn't a "main", then the tasklet in "current" is merely a
* runnable one
*/
if (ts != NULL) {
t = ts->st.current;
if (t && t != ts->st.main && ts->st.main != NULL) {
#if SIZEOF_VOID_P > SIZEOF_LONG
return (unsigned long)((Py_intptr_t)t) ^ (unsigned long)((Py_intptr_t)t >> 32);
#else
return (unsigned long)t;
#endif
}
}
/* We want the ID to be constant, before and after a main tasklet
* is initialized on a thread.Therefore, for a main tasklet, we use its
* thread ID.
*/
if (ts)
return ts->thread_id;
return PyThread_get_thread_ident();
}
static PyObject *
getcurrentid(PyObject *self, PyObject *unused)
{
return PyLong_FromUnsignedLong(PyStackless_GetCurrentId());
}
PyDoc_STRVAR(getmain__doc__,
"getmain() -- return the main tasklet of this thread.");
static PyObject *
getmain(PyObject *self, PyObject *unused)
{
PyThreadState *ts = _PyThreadState_GET();
PyObject * t = (PyObject*) ts->st.main;
Py_INCREF(t);
return t;
}
PyDoc_STRVAR(enable_soft__doc__,
"enable_softswitch(flag) -- control the switching behavior.\n"
"Tasklets can be either switched by moving C stack slices around\n"
"or by avoiding stack changes at all. The latter is only possible\n"
"in the top interpreter level. Switching it off is for timing and\n"
"debugging purposes. This flag exists once for the whole process.\n"
"For inquiry only, use 'None' as the flag.\n"
"By default, soft switching is enabled.");
static PyObject *
enable_softswitch(PyObject *self, PyObject *flag)
{
PyThreadState *ts = _PyThreadState_GET();
PyObject *ret;
int newflag;
if (!flag || flag == Py_None)
return PyBool_FromLong(ts->interp->st.enable_softswitch);
newflag = PyObject_IsTrue(flag);
if (newflag == -1 && PyErr_Occurred())
return NULL;
ret = PyBool_FromLong(ts->interp->st.enable_softswitch);
ts->interp->st.enable_softswitch = !!newflag;
return ret;
}
PyDoc_STRVAR(run_watchdog__doc__,
"run_watchdog(timeout=0, threadblock=False, soft=False,\n\
ignore_nesting=False, totaltimeout=False) -- \n\
run tasklets until they are all\n\
done, or timeout instructions have passed, if timeout is not 0.\n\
Tasklets must provide cooperative schedule() calls.\n\
If the timeout is met, the function returns.\n\
This function must be called from the main tasklet only.\n\
If a tasklet is interrupted, it is returned as the return value of the\n\
function.\n\
If an exception occours, it will be passed to the main tasklet.\n\
The other optional flags paremeter work as follows:\n\
threadblock: When set, ensures, that the thread\n\
will block when it runs out of tasklets to await channel activity from\n\
other Python(r) threads to wake it up.\n\
soft: When set, tasklets won't be interrupted but\n\
run will return (with a None) at the next convenient scheduling moment\n\
when the timeout has occurred.\n\
ignore_nesting: Allow interrupts at any interpreter nesting level,\n\
ignoring the tasklets' own ignore_nesting attribute.\n\
totaltimeout: The 'timeout' argument is the total timeout for run(),\n\
rather than a maximum timeslice for a single tasklet. This for run()\n\
to return after a certain time.");
static PyObject *
interrupt_timeout_return(void)
{
PyThreadState *ts = _PyThreadState_GET();
PyTaskletObject *current = ts->st.current;
PyTaskletObject *watchdog;
PyObject *ret;
/*
* we mark the IRQ as pending if
* a) we are in soft interrupt mode
* b) we are in hard interrupt mode, but aren't allowed to break here which happens
* when "atomic" is set, or the "nesting level" is relevant and not ignored.
* Also, when switch trapped, we don't perform an involountary switch.
*/
if ((ts->st.runflags & PY_WATCHDOG_SOFT) ||
current->flags.atomic || ts->st.schedlock ||
!TASKLET_NESTING_OK(current) ||
ts->st.switch_trap)
{
ts->st.tick_watermark = ts->st.tick_counter + ts->st.interval;
current->flags.pending_irq = 1;
Py_INCREF(Py_None);
return Py_None;
}
else
current->flags.pending_irq = 0;
/* interrupt! Signal that an interrupt has indeed taken place */
assert(ts->st.interrupted == NULL);
ts->st.interrupted = (PyObject*)ts->st.current;
Py_INCREF(ts->st.interrupted);
/* switch to the watchdog tasklet */
watchdog = slp_get_watchdog(ts, 1);
slp_schedule_task(&ret, ts->st.current, watchdog, 1, 0);
return ret;
}
static PyObject *
run_watchdog(PyObject *self, PyObject *args, PyObject *kwds);
static PyObject *
PyStackless_RunWatchdog_M(long timeout, long flags)
{
PyMethodDef def = {"run", (PyCFunction)(void(*)(void))run_watchdog, METH_VARARGS | METH_KEYWORDS};
int threadblock, soft, ignore_nesting, totaltimeout;
threadblock = (flags & Py_WATCHDOG_THREADBLOCK) ? 1 : 0;
soft = (flags & PY_WATCHDOG_SOFT) ? 1 : 0;
ignore_nesting=(flags & PY_WATCHDOG_IGNORE_NESTING) ? 1 : 0;
totaltimeout =(flags & PY_WATCHDOG_TOTALTIMEOUT) ? 1 : 0;
return PyStackless_CallCMethod_Main(&def, NULL, "liii",
timeout, threadblock, soft, ignore_nesting, totaltimeout);
}
PyObject *
PyStackless_RunWatchdog(long timeout)
{
return PyStackless_RunWatchdogEx(timeout, 0);
}
static int
push_watchdog(PyThreadState *ts, PyTaskletObject *t, int *interrupt);
static PyTaskletObject *
pop_watchdog(PyThreadState *ts);
static int
check_watchdog(PyThreadState *ts, PyTaskletObject *task);
PyObject *
PyStackless_RunWatchdogEx(long timeout, int flags)
{
PyThreadState *ts = _PyThreadState_GET();
PyTaskletObject *old_current, *victim;
PyObject *retval;
int fail;
PyObject* (*old_interrupt)(void) = NULL;
int old_runflags = 0;
long old_watermark = 0, old_interval = 0;
int interrupt;
if (flags < 0 || flags >= (1 << (sizeof(ts->st.runflags) * CHAR_BIT))) {
PyErr_SetString(PyExc_ValueError, "flags must be in [0..255]");
return NULL;
}
if (ts->st.main == NULL)
return PyStackless_RunWatchdog_M(timeout, flags);
/* is this an interrupt watchdog? Treat it differently. */
interrupt = timeout > 0;
/* push the current tasklet onto the watchdog stack */
if (push_watchdog(ts, ts->st.current, &interrupt))
return NULL;
old_current = ts->st.current;
/* store watchdog state and set up a new one, if we are the active interrupt watchdog */
if (interrupt) {
old_interrupt = ts->st.interrupt;
old_runflags = ts->st.runflags;
old_watermark = ts->st.tick_watermark;
old_interval = ts->st.interval;
if (timeout <= 0)
ts->st.interrupt = NULL;
else
ts->st.interrupt = interrupt_timeout_return;
ts->st.interval = timeout;
ts->st.tick_watermark = ts->st.tick_counter + timeout;
ts->st.runflags = flags;
}
/* run the watchdog */
Py_DECREF(ts->st.current);
slp_current_remove(); /* it still exists in the watchdog stack */
fail = slp_schedule_task(&retval, old_current, ts->st.current, 0, 0);
if (fail) {
/* we failed to switch */
PyTaskletObject *undo = pop_watchdog(ts);
if (NULL == undo)
return NULL;
assert(undo == old_current);
/* In case of an error, we don't know the state */
if (undo->next == NULL)
slp_current_unremove(undo);
return NULL;
}
/* we are back in the original tasklet */
assert(old_current == ts->st.current);
if (check_watchdog(ts, old_current)) {
/* we were awoken. But if there are deeper tasklets on the stack, we pop them here
* and make them runnable. Those that are popped here by us, will know this because
* when they wake up, they won't be on the stack anymore
*/
for(;;) {
PyTaskletObject *popped = pop_watchdog(ts);
if (!PyTasklet_Scheduled(popped))
/* popped a deeper tasklet, that hasn't been scheduled meanwhile */
slp_current_insert(popped); /* steals reference */
else {
/* Usually only the current tasklet.
* But also a deeper tasklet, that got scheduled (e.g. by taskler.insert())
*/
Py_DECREF(popped);
}
if (popped == old_current)
break;
}
if (interrupt) {
ts->st.interrupt = old_interrupt;
ts->st.runflags = old_runflags;
ts->st.tick_watermark = old_watermark;
ts->st.interval = old_interval;
}
}
/* retval really should be PyNone here (or NULL). Technically, it is the
* tempval of some tasklet that has quit. Even so, it is quite
* useless to use. run() must return None, or a tasklet
*/
if (retval == NULL)
return NULL;
Py_DECREF(retval);
/*
* If we were interrupted and using hard interrupts (bit 1 in flags not set)
* we need to return the interrupted tasklet)
*/
if (ts->st.interrupted) {
victim = (PyTaskletObject*)ts->st.interrupted;
ts->st.interrupted = NULL;
if (!(flags & PY_WATCHDOG_SOFT)) {
/* remove victim from runnable queue */
slp_current_remove_tasklet(victim);
Py_DECREF(victim); /* the ref from the runqueue */
return (PyObject*) victim;
} else
/* soft interrupt just leave the victim in place */
Py_DECREF(victim);
}
Py_RETURN_NONE;
}
static int
push_watchdog(PyThreadState *ts, PyTaskletObject *t, int *interrupt)
{
/* push ourselves on the stack of watchdogs.
* The zeroeth member is special, it is the tasklet that should be
* interrupted if the watchdog timer times out. All the others
* are awoken in case the run-queue empties in a top-down fashion
*/
if (ts->st.watchdogs == NULL) {
/* initialize it with a PyNone in theinterrupt slot */
ts->st.watchdogs = PyList_New(1);
if (ts->st.watchdogs == NULL)
return -1;
Py_INCREF(Py_None);
PyList_SET_ITEM(ts->st.watchdogs, 0, Py_None);
}
if (*interrupt) {
/* the caller is requesting to be the interrupt watchdog. Let's see: */
if (PyList_GET_ITEM(ts->st.watchdogs, 0) != Py_None) {
/* no, someone else already is the interrupt watchdog */
*interrupt = 0;
} else {
Py_INCREF(t);
if (PyList_SetItem(ts->st.watchdogs, 0, (PyObject *)t))
return -1;
}
}
if (PyList_Append(ts->st.watchdogs, (PyObject*) t))
return -1;
return 0;
}
static PyTaskletObject *
pop_watchdog(PyThreadState *ts)
{
PyTaskletObject *t;
Py_ssize_t s;
if (ts->st.watchdogs == NULL || (s = PyList_GET_SIZE(ts->st.watchdogs)) == 1) {
PyErr_SetNone(PyExc_ValueError);
return NULL;
}
t = (PyTaskletObject*) PyList_GET_ITEM(ts->st.watchdogs, s - 1);
Py_INCREF(t);
if (PyList_SetSlice(ts->st.watchdogs, s - 1, s, NULL)) {
Py_DECREF(t);
return NULL;
}
if ((PyObject *)t == PyList_GET_ITEM(ts->st.watchdogs, 0)) {
/* clear it from the interrupt slot too */
Py_INCREF(Py_None);
if(PyList_SetItem(ts->st.watchdogs, 0, Py_None)) {
Py_DECREF(t);
return NULL;
}
}
return t;
}
/* check if a tasklet is on the watchdog stack */
static int
check_watchdog(PyThreadState *ts, PyTaskletObject *task)
{
Py_ssize_t i = ts->st.watchdogs ? PyList_GET_SIZE(ts->st.watchdogs) : 0;
/* we don't check the "intterupt" slot, number 0 */
while (i > 1) {
if (PyList_GET_ITEM(ts->st.watchdogs, i-1) == (PyObject*)task)
return 1;
--i;
}
return 0;
}
/* find the correct target to wake up when we block. The innermost watchdog
* or the main tasklet. Returns a borrowed reference
* if "interrupt" is set, then we want the tasklet running the outermost
* true watchdog, i.e. the one with interrupt conditions set.
*/
PyTaskletObject *
slp_get_watchdog(PyThreadState *ts, int interrupt)
{
PyTaskletObject *t;
/* TODO: treat interrupt differently */
if (ts->st.watchdogs == NULL || PyList_GET_SIZE(ts->st.watchdogs) == 1)
return ts->st.main;
if (interrupt) {
t = (PyTaskletObject*)PyList_GET_ITEM(ts->st.watchdogs, 0);
if ((PyObject*)t == Py_None)
t = ts->st.main; /* strange, there should be no interrupt in this case! */
return t;
}
return (PyTaskletObject*)PyList_GET_ITEM(
ts->st.watchdogs, PyList_GET_SIZE(ts->st.watchdogs) - 1);
}
static PyObject *
run_watchdog(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *argnames[] = {"timeout", "threadblock", "soft",
"ignore_nesting", "totaltimeout",
NULL};
long timeout = 0;
int threadblock = 0;
int soft = 0;
int ignore_nesting = 0;
int totaltimeout = 0;
int flags;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|liiii:run_watchdog",
argnames, &timeout, &threadblock, &soft,
&ignore_nesting, &totaltimeout))
return NULL;
flags = threadblock ? Py_WATCHDOG_THREADBLOCK : 0;
flags |= soft ? PY_WATCHDOG_SOFT : 0;
flags |= ignore_nesting ? PY_WATCHDOG_IGNORE_NESTING : 0;
flags |= totaltimeout ? PY_WATCHDOG_TOTALTIMEOUT : 0;
return PyStackless_RunWatchdogEx(timeout, flags);
}
PyDoc_STRVAR(get_thread_info__doc__,
"get_thread_info(thread_id) -- return a 3-tuple of the thread's\n\
main tasklet, current tasklet and runcount.\n\
To obtain a list of all thread infos, use\n\
\n\
map (stackless.get_thread_info, stackless.threads)");
static PyObject *
get_thread_info(PyObject *self, PyObject *args)
{
PyThreadState *ts = _PyThreadState_GET();
PyInterpreterState *interp = ts->interp;
PyObject *thread_id = NULL;
unsigned long id = 0;
long id_is_valid;
/* The additional optional argument flags is currently intentionally
* undocumented. The lower order flag bits are reserved for future public
* applications.
* If the flag bit 30 is set, the values of serial, serial_last_jump and
* initial_stub are appended to the result. The Stackless test suite uses them.
* If the flag bit 31 is set, the watchdog list is appended to the result.
* The Stackless test suite uses this feature to ensure that the list is empty at
* start and end of each test.
*/
unsigned long flags=0;
PyObject *retval;
if (!PyArg_ParseTuple(args, "|O!k:get_thread_info", &PyLong_Type, &thread_id, &flags))
return NULL;
id_is_valid = slp_parse_thread_id(thread_id, &id);
if (!id_is_valid)
return NULL;
if (id_is_valid == 1) {
SLP_HEAD_LOCK();
for (ts = interp->tstate_head; id && ts != NULL; ts = ts->next) {
if (ts->thread_id == id)
break;
}
SLP_HEAD_UNLOCK();
if (ts == NULL)
RUNTIME_ERROR("Thread id not found", NULL);
}
retval = Py_BuildValue("(OOi)",
ts->st.main ? (PyObject *) ts->st.main : Py_None,
ts->st.runcount ? (PyObject *) ts->st.current : Py_None,
ts->st.runcount
);
if (retval && (flags & (1ul<<30))) {
Py_ssize_t retsize = PyTuple_GET_SIZE(retval);
/* Append the serial numbers */
PyObject *serial, *serial_last_jump;
serial = PyLong_FromLongLong(ts->st.serial);
if (serial == NULL) {
Py_DECREF(retval);
return NULL;
}
serial_last_jump = PyLong_FromLongLong(ts->st.serial_last_jump);
if (serial == NULL) {
Py_DECREF(retval);
return NULL;
}
if (!_PyTuple_Resize(&retval, retsize + 3)) {
PyTuple_SET_ITEM(retval, retsize, serial); /* steals a ref to serial */
PyTuple_SET_ITEM(retval, retsize + 1, serial_last_jump); /* steals a ref to serial_last_jump */
serial = ts->st.initial_stub ? (PyObject *) ts->st.initial_stub : Py_None;
Py_INCREF(serial);
PyTuple_SET_ITEM(retval, retsize + 2, serial); /* steals a ref to serial */
}
}
if (retval && (flags & (1ul<<31))) {
Py_ssize_t retsize = PyTuple_GET_SIZE(retval);
/* Append the watchdog list */
if (!_PyTuple_Resize(&retval, retsize + 1)) {
PyObject *o = ts->st.watchdogs ? ts->st.watchdogs : Py_None;
Py_INCREF(o);
PyTuple_SET_ITEM(retval, retsize, o); /* steals a ref to o */
}
}
return retval;
}
static PyObject *
slpmodule_reduce(PyObject *self, PyObject *value)
{
if (value && !PyLong_Check(value)) {
PyErr_SetString(PyExc_TypeError, "__reduce_ex__ argument should be an integer");
return NULL;
}
return PyUnicode_FromString("_stackless");
}
int
PyStackless_AdjustSwitchTrap(int change)
{
PyThreadState *ts = _PyThreadState_GET();
int old = ts->st.switch_trap;
ts->st.switch_trap += change;
return old;
}
PyDoc_STRVAR(slpmodule_switch_trap__doc__,
"switch_trap(change) -- Change the switch trap level of the thread. When non-zero, \n\
tasklet switches won't take place. Instead, an exception is raised.\n\
Returns the old trap value. Defaults to 0.");
static PyObject *
slpmodule_switch_trap(PyObject *self, PyObject *args)
{
int change = 0;
if (!PyArg_ParseTuple(args, "|i", &change))
return NULL;
return PyLong_FromLong(PyStackless_AdjustSwitchTrap(change));
}
PyDoc_STRVAR(set_error_handler__doc__,
"set_error_handler(handler) -- Set or delete the error handler function \n\
used for uncaught exceptions on tasklets. \"handler\" should take three \n\
arguments: \"def handler(type, value, tb):\". Its return value is ignored.\n\
If \"handler\" is None, the default handler is used, which raises the error \n\
on the main tasklet. Similarly if the handler itself raises an error.\n\
Returns the previous handler or None.");
static PyObject *
set_error_handler(PyObject *self, PyObject *args)
{
PyObject *old, *handler = NULL;
PyThreadState * ts = _PyThreadState_GET();
if (!PyArg_ParseTuple(args, "|O:set_error_handler", &handler))
return NULL;
old = ts->interp->st.error_handler;
if (old == NULL)
old = Py_None;
Py_INCREF(old);
if (handler == Py_None)
handler = NULL;
Py_XINCREF(handler);
Py_XSETREF(ts->interp->st.error_handler, handler);
return old;
}
int
PyStackless_CallErrorHandler(void)
{
PyThreadState * ts = _PyThreadState_GET();
PyObject * error_handler = ts->interp->st.error_handler;
int res = -1; /* just raise the current exception */
PyObject *exc, *val, *tb;
PyObject *result;
assert(PyErr_Occurred());
if (error_handler == NULL)
return res;
Py_INCREF(error_handler); /* Own a ref while calling the handler! */
PyErr_Fetch(&exc, &val, &tb); /* we own the refs in exc, val and tb */
assert(exc != NULL);
if (!val) {
Py_INCREF(Py_None);
val = Py_None;
}
if (!tb) {
Py_INCREF(Py_None);
tb = Py_None;
}
result = PyObject_CallFunction(error_handler, "OOO", exc, val, tb);
if (result)
res = 0;
Py_DECREF(error_handler);
Py_DECREF(exc);
Py_DECREF(val);
Py_DECREF(tb);
Py_XDECREF(result);
return res;
}
/******************************************************
Some test functions, which access internal API
Other testfunctions go to _teststackless.c
******************************************************/
PyDoc_STRVAR(_test_outside__doc__,
"_test_outside() -- a builtin testing function.\n\
This function simulates an application that does not run \"inside\"\n\
Stackless, with active, running frames, but always needs to initialize\n\
the main tasklet to get \"inside\".\n\
The function will terminate when no other tasklets are runnable.\n\
\n\
Typical usage: Create a tasklet for test_cframe and run by _test_outside().\n\
\n\
t1 = tasklet(test_cframe)(1000000)\n\
_test_outside()\n\
This can be used to measure the execution time of 1.000.000 switches.");
static
PyObject *
_test_outside(PyObject *self, PyObject *unused)
{
PyThreadState *ts = _PyThreadState_GET();
PyTaskletObject *stmain = ts->st.main;
if (PyTasklet_Scheduled(stmain) && !PyTasklet_IsCurrent(stmain))
RUNTIME_ERROR("main tasklet is still scheduled", NULL);
PyTaskletObject *current;
PyCStackObject *initial_stub = ts->st.initial_stub;
PyFrameObject *f = SLP_CURRENT_FRAME(ts);
int recursion_depth = ts->recursion_depth;
int nesting_level = ts->st.nesting_level;
intptr_t *cstack_base = ts->st.cstack_base;
intptr_t *cstack_root = ts->st.cstack_root;
PyObject *ret = Py_None;
PY_LONG_LONG jump = ts->st.serial_last_jump;
Py_INCREF(ret);
ts->st.main = NULL;
assert(initial_stub->startaddr == cstack_base);
if (ts->interp != _PyRuntime.interpreters.main) {
ts->st.cstack_base = NULL;
ts->st.cstack_root = NULL;
}
ts->st.initial_stub = NULL;
ts->st.nesting_level = 0;
SLP_SET_CURRENT_FRAME(ts, NULL);
ts->recursion_depth = 0;
current = slp_current_remove();
while (ts->st.runcount > 0) {
Py_DECREF(ret);
ret = PyStackless_Schedule(Py_None, 0);
if (ret == NULL) {
break;
}
}
ts->st.cstack_base = cstack_base;
ts->st.cstack_root = cstack_root;
initial_stub->startaddr = cstack_base;
ts->st.main = stmain;
Py_CLEAR(ts->st.initial_stub);
ts->st.initial_stub = initial_stub;
SLP_SET_CURRENT_FRAME(ts, f);
slp_current_insert(current);
ts->recursion_depth = recursion_depth;
ts->st.nesting_level = nesting_level;
ts->st.serial_last_jump = jump;
return ret;
}
PyDoc_STRVAR(_test_cframe_nr__doc__,
"_test_cframe_nr(switches) -- a builtin testing function that does nothing\n\
but soft tasklet switching. The function will call PyStackless_Schedule_nr() for switches\n\
times and then finish.\n\
All remaining arguments are intentionally undocumented. Don't use them!\n\
Usage: Cf. test_cframe().");