gh-115999: Add free-threaded specialization for UNPACK_SEQUENCE (#126600)

Add free-threaded specialization for `UNPACK_SEQUENCE` opcode.
`UNPACK_SEQUENCE_TUPLE/UNPACK_SEQUENCE_TWO_TUPLE` are already thread safe since tuples are immutable.
`UNPACK_SEQUENCE_LIST` is not thread safe because of nature of lists (there is nothing preventing another thread from adding items to or removing them the list while the instruction is executing). To achieve thread safety we add a critical section to the implementation of `UNPACK_SEQUENCE_LIST`, especially around the parts where we check the size of the list and push items onto the stack.


---------

Co-authored-by: Matt Page <mpage@meta.com>
Co-authored-by: mpage <mpage@cs.stanford.edu>
This commit is contained in:
Kirill Podoprigora 2024-11-22 19:00:35 +02:00 committed by GitHub
parent 5ba67af006
commit 27486c3365
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 103 additions and 30 deletions

View file

@ -2487,39 +2487,33 @@ _Py_Specialize_UnpackSequence(_PyStackRef seq_st, _Py_CODEUNIT *instr, int oparg
{
PyObject *seq = PyStackRef_AsPyObjectBorrow(seq_st);
assert(ENABLE_SPECIALIZATION);
assert(ENABLE_SPECIALIZATION_FT);
assert(_PyOpcode_Caches[UNPACK_SEQUENCE] ==
INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE);
_PyUnpackSequenceCache *cache = (_PyUnpackSequenceCache *)(instr + 1);
if (PyTuple_CheckExact(seq)) {
if (PyTuple_GET_SIZE(seq) != oparg) {
SPECIALIZATION_FAIL(UNPACK_SEQUENCE, SPEC_FAIL_EXPECTED_ERROR);
goto failure;
unspecialize(instr);
return;
}
if (PyTuple_GET_SIZE(seq) == 2) {
instr->op.code = UNPACK_SEQUENCE_TWO_TUPLE;
goto success;
specialize(instr, UNPACK_SEQUENCE_TWO_TUPLE);
return;
}
instr->op.code = UNPACK_SEQUENCE_TUPLE;
goto success;
specialize(instr, UNPACK_SEQUENCE_TUPLE);
return;
}
if (PyList_CheckExact(seq)) {
if (PyList_GET_SIZE(seq) != oparg) {
SPECIALIZATION_FAIL(UNPACK_SEQUENCE, SPEC_FAIL_EXPECTED_ERROR);
goto failure;
unspecialize(instr);
return;
}
instr->op.code = UNPACK_SEQUENCE_LIST;
goto success;
specialize(instr, UNPACK_SEQUENCE_LIST);
return;
}
SPECIALIZATION_FAIL(UNPACK_SEQUENCE, unpack_sequence_fail_kind(seq));
failure:
STAT_INC(UNPACK_SEQUENCE, failure);
instr->op.code = UNPACK_SEQUENCE;
cache->counter = adaptive_counter_backoff(cache->counter);
return;
success:
STAT_INC(UNPACK_SEQUENCE, success);
cache->counter = adaptive_counter_cooldown();
unspecialize(instr);
}
#ifdef Py_STATS