bytes.join方法的实现,实现
here包括在迭代期间防止大小更改的代码:
if (seqlen != PySequence_Fast_GET_SIZE(seq)) {
PyErr_SetString(PyExc_RuntimeError,
"sequence changed size during iteration");
goto error;
}
如何修改bytes.join调用中的可迭代序列以及为什么上述代码是必要的?或者它可能没有必要和冗余?
最佳答案 如果将列表对象传入bytes.join(),则可能会在bytes.join()调用迭代时将元素添加到另一个线程的列表中.
bytes.join()方法必须对序列进行两次传递;一次计算包含的字节对象的总长度,第二次再构建实际的输出字节对象.在迭代它时改变项目数量会使扳手进入该计算.
您通常无法对列表执行此操作,因为GIL未释放,但如果列表中的任何对象不是字节对象,则使用buffer protocol.如a comment on the original patch states:
The problem with your approach is that the sequence could be mutated while another thread is running (
_getbuffer()
may release the GIL). Then the pre-computed size gets wrong.