GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cpython/Python/context.c at main · python/cpython Expand file tree/ Copy pathcontext.cMore file actions 1454 lines (1196 loc) · 35.2 KB / Copy pathcontext.cFile metadata and controls1454 lines (1196 loc) · 35.2 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 #include "Python.h" #include "pycore_call.h" // _PyObject_VectorcallTstate() #include "pycore_context.h" #include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION() #include "pycore_freelist.h" // _Py_FREELIST_FREE(), _Py_FREELIST_POP() #include "pycore_gc.h" // _PyObject_GC_MAY_BE_TRACKED() #include "pycore_hamt.h" #include "pycore_initconfig.h" // _PyStatus_OK() #include "pycore_object.h" #include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_INT_RELAXED() #include "pycore_pyerrors.h" #include "pycore_pystate.h" // _PyThreadState_GET() #include "clinic/context.c.h" /*[clinic input] module _contextvars [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=a0955718c8b8cea6]*/ #define ENSURE_Context(o, err_ret) \ if (!PyContext_CheckExact(o)) { \ PyErr_SetString(PyExc_TypeError, \ "an instance of Context was expected"); \ return err_ret; \ } #define ENSURE_ContextVar(o, err_ret) \ if (!PyContextVar_CheckExact(o)) { \ PyErr_SetString(PyExc_TypeError, \ "an instance of ContextVar was expected"); \ return err_ret; \ } #define ENSURE_ContextToken(o, err_ret) \ if (!PyContextToken_CheckExact(o)) { \ PyErr_SetString(PyExc_TypeError, \ "an instance of Token was expected"); \ return err_ret; \ } /////////////////////////// Context API static PyContext * context_new_empty(void); static PyContext * context_new_from_vars(PyHamtObject *vars); static inline PyContext * context_get(void); static PyContextToken * token_new(PyContext *ctx, PyContextVar *var, PyObject *val); static PyContextVar * contextvar_new(PyObject *name, PyObject *def); static int contextvar_set(PyContextVar *var, PyObject *val); static int contextvar_del(PyContextVar *var); static inline PyHamtObject * context_get_vars(PyContext *ctx) { PyHamtObject *vars; Py_BEGIN_CRITICAL_SECTION(ctx); vars = ctx->ctx_vars; assert(vars != NULL); Py_INCREF(vars); Py_END_CRITICAL_SECTION(); return vars; } static inline PyHamtObject * context_get_current_vars(PyContext *ctx) { // ctx_vars written only by the owning thread, and read by other threads // only under the context's lock, a plain (non-atomic) load is okay PyHamtObject *vars = ctx->ctx_vars; assert(vars != NULL); return vars; } // Note: steals a reference to new_vars and must only be called by the thread // that has `ctx` as its current context. static inline void context_set_vars(PyContext *ctx, PyHamtObject *new_vars) { PyHamtObject *old_vars; Py_BEGIN_CRITICAL_SECTION(ctx); old_vars = ctx->ctx_vars; ctx->ctx_vars = new_vars; Py_END_CRITICAL_SECTION(); Py_XDECREF(old_vars); } PyObject * _PyContext_NewHamtForTests(void) { return (PyObject *)_PyHamt_New(); } PyObject * PyContext_New(void) { return (PyObject *)context_new_empty(); } PyObject * PyContext_Copy(PyObject * octx) { ENSURE_Context(octx, NULL) PyContext *ctx = (PyContext *)octx; PyHamtObject *vars = context_get_vars(ctx); PyObject *res = (PyObject *)context_new_from_vars(vars); Py_DECREF(vars); return res; } PyObject * PyContext_CopyCurrent(void) { PyContext *ctx = context_get(); if (ctx == NULL) { return NULL; } return (PyObject *)context_new_from_vars(context_get_current_vars(ctx)); } static const char * context_event_name(PyContextEvent event) { switch (event) { case Py_CONTEXT_SWITCHED: return "Py_CONTEXT_SWITCHED"; default: return "?"; } Py_UNREACHABLE(); } static void notify_context_watchers(PyThreadState *ts, PyContextEvent event, PyObject *ctx) { if (ctx == NULL) { // This will happen after exiting the last context in the stack, which // can occur if context_get was never called before entering a context // (e.g., called `contextvars.Context().run()` on a fresh thread, as // PyContext_Enter doesn't call context_get). ctx = Py_None; } assert(Py_REFCNT(ctx) > 0); PyInterpreterState *interp = ts->interp; assert(interp->_initialized); uint8_t bits = interp->active_context_watchers; int i = 0; while (bits) { assert(i < CONTEXT_MAX_WATCHERS); if (bits & 1) { PyContext_WatchCallback cb = interp->context_watchers[i]; // A previous callback may have cleared this watcher. if (cb != NULL && cb(event, ctx) < 0) { PyErr_FormatUnraisable( "Exception ignored in %s watcher callback for %R", context_event_name(event), ctx); } } i++; bits >>= 1; } } int PyContext_AddWatcher(PyContext_WatchCallback callback) { PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->_initialized); for (int i = 0; i < CONTEXT_MAX_WATCHERS; i++) { if (!interp->context_watchers[i]) { interp->context_watchers[i] = callback; interp->active_context_watchers |= (1 << i); return i; } } PyErr_SetString(PyExc_RuntimeError, "no more context watcher IDs available"); return -1; } int PyContext_ClearWatcher(int watcher_id) { PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->_initialized); if (watcher_id < 0 || watcher_id >= CONTEXT_MAX_WATCHERS) { PyErr_Format(PyExc_ValueError, "Invalid context watcher ID %d", watcher_id); return -1; } if (!interp->context_watchers[watcher_id]) { PyErr_Format(PyExc_ValueError, "No context watcher set for ID %d", watcher_id); return -1; } interp->context_watchers[watcher_id] = NULL; interp->active_context_watchers &= ~(1 << watcher_id); return 0; } static inline void context_switched(PyThreadState *ts) { ts->context_ver++; // ts->context is used instead of context_get() because context_get() might // throw if ts->context is NULL. notify_context_watchers(ts, Py_CONTEXT_SWITCHED, ts->context); } int _PyContext_Enter(PyThreadState *ts, PyObject *octx) { ENSURE_Context(octx, -1) PyContext *ctx = (PyContext *)octx; #ifdef Py_GIL_DISABLED int already_entered = _Py_atomic_exchange_int(&ctx->ctx_entered, 1); #else int already_entered = ctx->ctx_entered; ctx->ctx_entered = 1; #endif if (already_entered) { _PyErr_Format(ts, PyExc_RuntimeError, "cannot enter context: %R is already entered", ctx); return -1; } ctx->ctx_prev = (PyContext *)ts->context; /* borrow */ ts->context = Py_NewRef(ctx); context_switched(ts); return 0; } int PyContext_Enter(PyObject *octx) { PyThreadState *ts = _PyThreadState_GET(); assert(ts != NULL); return _PyContext_Enter(ts, octx); } int _PyContext_Exit(PyThreadState *ts, PyObject *octx) { ENSURE_Context(octx, -1) PyContext *ctx = (PyContext *)octx; int already_entered = FT_ATOMIC_LOAD_INT_RELAXED(ctx->ctx_entered); if (!already_entered) { PyErr_Format(PyExc_RuntimeError, "cannot exit context: %R has not been entered", ctx); return -1; } if (ts->context != (PyObject *)ctx) { /* Can only happen if someone misuses the C API */ PyErr_SetString(PyExc_RuntimeError, "cannot exit context: thread state references " "a different context object"); return -1; } Py_SETREF(ts->context, (PyObject *)ctx->ctx_prev); ctx->ctx_prev = NULL; FT_ATOMIC_STORE_INT(ctx->ctx_entered, 0); context_switched(ts); return 0; } int PyContext_Exit(PyObject *octx) { PyThreadState *ts = _PyThreadState_GET(); assert(ts != NULL); return _PyContext_Exit(ts, octx); } PyObject * PyContextVar_New(const char *name, PyObject *def) { PyObject *pyname = PyUnicode_FromString(name); if (pyname == NULL) { return NULL; } PyContextVar *var = contextvar_new(pyname, def); Py_DECREF(pyname); return (PyObject *)var; } int PyContextVar_Get(PyObject *ovar, PyObject *def, PyObject **val) { ENSURE_ContextVar(ovar, -1) PyContextVar *var = (PyContextVar *)ovar; PyThreadState *ts = _PyThreadState_GET(); assert(ts != NULL); if (ts->context == NULL) { goto not_found; } #ifndef Py_GIL_DISABLED if (var->var_cached != NULL && var->var_cached_tsid == ts->id && var->var_cached_tsver == ts->context_ver) { *val = var->var_cached; goto found; } #endif assert(PyContext_CheckExact(ts->context)); PyHamtObject *vars = context_get_current_vars((PyContext *)ts->context); PyObject *found = NULL; int res = _PyHamt_Find(vars, (PyObject*)var, &found); if (res < 0) { goto error; } if (res == 1) { assert(found != NULL); #ifndef Py_GIL_DISABLED var->var_cached = found; /* borrow */ var->var_cached_tsid = ts->id; var->var_cached_tsver = ts->context_ver; #endif *val = found; goto found; } not_found: if (def == NULL) { if (var->var_default != NULL) { *val = var->var_default; goto found; } *val = NULL; goto found; } else { *val = def; goto found; } found: Py_XINCREF(*val); return 0; error: *val = NULL; return -1; } PyObject * PyContextVar_Set(PyObject *ovar, PyObject *val) { ENSURE_ContextVar(ovar, NULL) PyContextVar *var = (PyContextVar *)ovar; PyContext *ctx = context_get(); if (ctx == NULL) { return NULL; } PyObject *old_val = NULL; int found = _PyHamt_Find(context_get_current_vars(ctx), (PyObject *)var, &old_val); if (found < 0) { return NULL; } Py_XINCREF(old_val); PyContextToken *tok = token_new(ctx, var, old_val); Py_XDECREF(old_val); if (tok == NULL) { return NULL; } if (contextvar_set(var, val)) { Py_DECREF(tok); return NULL; } return (PyObject *)tok; } int PyContextVar_Reset(PyObject *ovar, PyObject *otok) { ENSURE_ContextVar(ovar, -1) ENSURE_ContextToken(otok, -1) PyContextVar *var = (PyContextVar *)ovar; PyContextToken *tok = (PyContextToken *)otok; if (tok->tok_used) { PyErr_Format(PyExc_RuntimeError, "%R has already been used once", tok); return -1; } if (var != tok->tok_var) { PyErr_Format(PyExc_ValueError, "%R was created by a different ContextVar", tok); return -1; } PyContext *ctx = context_get(); if (ctx != tok->tok_ctx) { PyErr_Format(PyExc_ValueError, "%R was created in a different Context", tok); return -1; } tok->tok_used = 1; if (tok->tok_oldval == NULL) { return contextvar_del(var); } else { return contextvar_set(var, tok->tok_oldval); } } /////////////////////////// PyContext /*[clinic input] class _contextvars.Context "PyContext *" "&PyContext_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdf87f8e0cb580e8]*/ #define _PyContext_CAST(op) ((PyContext *)(op)) static inline PyContext * _context_alloc(void) { PyContext *ctx = _Py_FREELIST_POP(PyContext, contexts); if (ctx == NULL) { ctx = PyObject_GC_New(PyContext, &PyContext_Type); if (ctx == NULL) { return NULL; } } ctx->ctx_vars = NULL; ctx->ctx_prev = NULL; ctx->ctx_entered = 0; ctx->ctx_weakreflist = NULL; return ctx; } static PyContext * context_new_empty(void) { PyContext *ctx = _context_alloc(); if (ctx == NULL) { return NULL; } ctx->ctx_vars = _PyHamt_New(); if (ctx->ctx_vars == NULL) { Py_DECREF(ctx); return NULL; } _PyObject_GC_TRACK(ctx); return ctx; } static PyContext * context_new_from_vars(PyHamtObject *vars) { PyContext *ctx = _context_alloc(); if (ctx == NULL) { return NULL; } ctx->ctx_vars = (PyHamtObject*)Py_NewRef(vars); _PyObject_GC_TRACK(ctx); return ctx; } static inline PyContext * context_get(void) { PyThreadState *ts = _PyThreadState_GET(); assert(ts != NULL); PyContext *current_ctx = (PyContext *)ts->context; if (current_ctx == NULL) { current_ctx = context_new_empty(); if (current_ctx == NULL) { return NULL; } ts->context = (PyObject *)current_ctx; } return current_ctx; } static int context_check_key_type(PyObject *key) { if (!PyContextVar_CheckExact(key)) { // abort(); PyErr_Format(PyExc_TypeError, "a ContextVar key was expected, got %R", key); return -1; } return 0; } static PyObject * context_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { if (PyTuple_Size(args) || (kwds != NULL && PyDict_Size(kwds))) { PyErr_SetString( PyExc_TypeError, "Context() does not accept any arguments"); return NULL; } return PyContext_New(); } static int context_tp_clear(PyObject *op) { PyContext *self = _PyContext_CAST(op); Py_CLEAR(self->ctx_prev); Py_CLEAR(self->ctx_vars); return 0; } static int context_tp_traverse(PyObject *op, visitproc visit, void *arg) { PyContext *self = _PyContext_CAST(op); Py_VISIT(self->ctx_prev); Py_VISIT(self->ctx_vars); return 0; } static void context_tp_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); PyContext *ctx = _PyContext_CAST(self); if (ctx->ctx_weakreflist != NULL) { PyObject_ClearWeakRefs(self); } (void)context_tp_clear(self); _Py_FREELIST_FREE(contexts, self, Py_TYPE(self)->tp_free); } static PyObject * context_tp_iter(PyObject *op) { PyContext *self = _PyContext_CAST(op); PyHamtObject *vars = context_get_vars(self); PyObject *res = _PyHamt_NewIterKeys(vars); Py_DECREF(vars); return res; } static PyObject * context_tp_richcompare(PyObject *v, PyObject *w, int op) { if (!PyContext_CheckExact(v) || !PyContext_CheckExact(w) || (op != Py_EQ && op != Py_NE)) { Py_RETURN_NOTIMPLEMENTED; } PyHamtObject *v_vars = context_get_vars((PyContext *)v); PyHamtObject *w_vars = context_get_vars((PyContext *)w); int res = _PyHamt_Eq(v_vars, w_vars); Py_DECREF(v_vars); Py_DECREF(w_vars); if (res < 0) { return NULL; } if (op == Py_NE) { res = !res; } if (res) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static Py_ssize_t context_tp_len(PyObject *op) { PyContext *self = _PyContext_CAST(op); PyHamtObject *vars = context_get_vars(self); Py_ssize_t res = _PyHamt_Len(vars); Py_DECREF(vars); return res; } static PyObject * context_tp_subscript(PyObject *op, PyObject *key) { if (context_check_key_type(key)) { return NULL; } PyObject *val = NULL; PyContext *self = _PyContext_CAST(op); PyHamtObject *vars = context_get_vars(self); int found = _PyHamt_Find(vars, key, &val); Py_XINCREF(val); Py_DECREF(vars); if (found < 0) { return NULL; } if (found == 0) { PyErr_SetObject(PyExc_KeyError, key); return NULL; } return val; } static int context_tp_contains(PyObject *op, PyObject *key) { if (context_check_key_type(key)) { return -1; } PyObject *val = NULL; PyContext *self = _PyContext_CAST(op); PyHamtObject *vars = context_get_vars(self); int res = _PyHamt_Find(vars, key, &val); Py_DECREF(vars); return res; } /*[clinic input] @permit_long_summary _contextvars.Context.get key: object default: object = None / Return the value for `key` if `key` has the value in the context object. If `key` does not exist, return `default`. If `default` is not given, return None. [clinic start generated code]*/ static PyObject * _contextvars_Context_get_impl(PyContext *self, PyObject *key, PyObject *default_value) /*[clinic end generated code: output=0c54aa7664268189 input=d669a0d56fabb0a5]*/ { if (context_check_key_type(key)) { return NULL; } PyObject *val = NULL; PyHamtObject *vars = context_get_vars(self); int found = _PyHamt_Find(vars, key, &val); Py_XINCREF(val); Py_DECREF(vars); if (found < 0) { return NULL; } if (found == 0) { return Py_NewRef(default_value); } return val; } /*[clinic input] _contextvars.Context.items Return all variables and their values in the context object. The result is returned as a list of 2-tuples (variable, value). [clinic start generated code]*/ static PyObject * _contextvars_Context_items_impl(PyContext *self) /*[clinic end generated code: output=fa1655c8a08502af input=00db64ae379f9f42]*/ { PyHamtObject *vars = context_get_vars(self); PyObject *res = _PyHamt_NewIterItems(vars); Py_DECREF(vars); return res; } /*[clinic input] _contextvars.Context.keys Return a list of all variables in the context object. [clinic start generated code]*/ static PyObject * _contextvars_Context_keys_impl(PyContext *self) /*[clinic end generated code: output=177227c6b63ec0e2 input=114b53aebca3449c]*/ { PyHamtObject *vars = context_get_vars(self); PyObject *res = _PyHamt_NewIterKeys(vars); Py_DECREF(vars); return res; } /*[clinic input] _contextvars.Context.values Return a list of all variables' values in the context object. [clinic start generated code]*/ static PyObject * _contextvars_Context_values_impl(PyContext *self) /*[clinic end generated code: output=d286dabfc8db6dde input=ce8075d04a6ea526]*/ { PyHamtObject *vars = context_get_vars(self); PyObject *res = _PyHamt_NewIterValues(vars); Py_DECREF(vars); return res; } /*[clinic input] _contextvars.Context.copy Return a shallow copy of the context object. [clinic start generated code]*/ static PyObject * _contextvars_Context_copy_impl(PyContext *self) /*[clinic end generated code: output=30ba8896c4707a15 input=ebafdbdd9c72d592]*/ { PyHamtObject *vars = context_get_vars(self); PyObject *res = (PyObject *)context_new_from_vars(vars); Py_DECREF(vars); return res; } static PyObject * context_run(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyThreadState *ts = _PyThreadState_GET(); if (nargs < 1) { _PyErr_SetString(ts, PyExc_TypeError, "run() missing 1 required positional argument"); return NULL; } if (_PyContext_Enter(ts, self)) { return NULL; } PyObject *call_result = _PyObject_VectorcallTstate( ts, args[0], args + 1, nargs - 1, kwnames); if (_PyContext_Exit(ts, self)) { Py_XDECREF(call_result); return NULL; } return call_result; } static PyMethodDef PyContext_methods[] = { _CONTEXTVARS_CONTEXT_GET_METHODDEF _CONTEXTVARS_CONTEXT_ITEMS_METHODDEF _CONTEXTVARS_CONTEXT_KEYS_METHODDEF _CONTEXTVARS_CONTEXT_VALUES_METHODDEF _CONTEXTVARS_CONTEXT_COPY_METHODDEF {"run", _PyCFunction_CAST(context_run), METH_FASTCALL | METH_KEYWORDS, NULL}, {NULL, NULL} }; static PySequenceMethods PyContext_as_sequence = { .sq_contains = context_tp_contains }; static PyMappingMethods PyContext_as_mapping = { .mp_length = context_tp_len, .mp_subscript = context_tp_subscript }; PyTypeObject PyContext_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "_contextvars.Context", sizeof(PyContext), .tp_methods = PyContext_methods, .tp_as_mapping = &PyContext_as_mapping, .tp_as_sequence = &PyContext_as_sequence, .tp_iter = context_tp_iter, .tp_dealloc = context_tp_dealloc, .tp_getattro = PyObject_GenericGetAttr, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, .tp_richcompare = context_tp_richcompare, .tp_traverse = context_tp_traverse, .tp_clear = context_tp_clear, .tp_new = context_tp_new, .tp_weaklistoffset = offsetof(PyContext, ctx_weakreflist), .tp_hash = PyObject_HashNotImplemented, }; /////////////////////////// ContextVar static int contextvar_set(PyContextVar *var, PyObject *val) { #ifndef Py_GIL_DISABLED var->var_cached = NULL; PyThreadState *ts = _PyThreadState_GET(); #endif PyContext *ctx = context_get(); if (ctx == NULL) { return -1; } // gh-148891: Make a strong reference so a GC during _PyHamt_Assoc will // not free the HAMT during traversal. PyHamtObject *old_vars = context_get_current_vars(ctx); Py_INCREF(old_vars); PyHamtObject *new_vars = _PyHamt_Assoc( old_vars, (PyObject *)var, val); Py_DECREF(old_vars); if (new_vars == NULL) { return -1; } #ifndef Py_GIL_DISABLED var->var_cached = val; /* borrow */ var->var_cached_tsid = ts->id; var->var_cached_tsver = ts->context_ver; #endif /* Releasing the old variables may run a finalizer that updates the cache. */ context_set_vars(ctx, new_vars); return 0; } static int contextvar_del(PyContextVar *var) { #ifndef Py_GIL_DISABLED var->var_cached = NULL; #endif PyContext *ctx = context_get(); if (ctx == NULL) { return -1; } // gh-148891: Make a strong reference so a GC during _PyHamt_Without will // not free the HAMT during traversal. PyHamtObject *vars = context_get_current_vars(ctx); Py_INCREF(vars); PyHamtObject *new_vars = _PyHamt_Without(vars, (PyObject *)var); Py_DECREF(vars); if (new_vars == NULL) { return -1; } if (vars == new_vars) { Py_DECREF(new_vars); PyErr_SetObject(PyExc_LookupError, (PyObject *)var); return -1; } context_set_vars(ctx, new_vars); return 0; } static Py_hash_t contextvar_generate_hash(void *addr, PyObject *name) { /* Take hash of `name` and XOR it with the object's addr. The structure of the tree is encoded in objects' hashes, which means that sufficiently similar hashes would result in tall trees with many Collision nodes. Which would, in turn, result in slower get and set operations. The XORing helps to ensure that: (1) sequentially allocated ContextVar objects have different hashes; (2) context variables with equal names have different hashes. */ Py_hash_t name_hash = PyObject_Hash(name); if (name_hash == -1) { return -1; } Py_hash_t res = Py_HashPointer(addr) ^ name_hash; return res == -1 ? -2 : res; } static PyContextVar * contextvar_new(PyObject *name, PyObject *def) { if (!PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "context variable name must be a str"); return NULL; } PyContextVar *var = PyObject_GC_New(PyContextVar, &PyContextVar_Type); if (var == NULL) { return NULL; } var->var_name = Py_NewRef(name); var->var_default = Py_XNewRef(def); #ifndef Py_GIL_DISABLED var->var_cached = NULL; var->var_cached_tsid = 0; var->var_cached_tsver = 0; #endif var->var_hash = contextvar_generate_hash(var, name); if (var->var_hash == -1) { Py_DECREF(var); return NULL; } if (_PyObject_GC_MAY_BE_TRACKED(name) || (def != NULL && _PyObject_GC_MAY_BE_TRACKED(def))) { PyObject_GC_Track(var); } return var; } /*[clinic input] class _contextvars.ContextVar "PyContextVar *" "&PyContextVar_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=445da935fa8883c3]*/ #define _PyContextVar_CAST(op) ((PyContextVar *)(op)) static PyObject * contextvar_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"", "default", NULL}; |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |