_queuemodule.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. #ifndef Py_BUILD_CORE_BUILTIN
  2. # define Py_BUILD_CORE_MODULE 1
  3. #endif
  4. #include "Python.h"
  5. #include "pycore_moduleobject.h" // _PyModule_GetState()
  6. #include "structmember.h" // PyMemberDef
  7. #include <stddef.h> // offsetof()
  8. typedef struct {
  9. PyTypeObject *SimpleQueueType;
  10. PyObject *EmptyError;
  11. } simplequeue_state;
  12. static simplequeue_state *
  13. simplequeue_get_state(PyObject *module)
  14. {
  15. simplequeue_state *state = _PyModule_GetState(module);
  16. assert(state);
  17. return state;
  18. }
  19. static struct PyModuleDef queuemodule;
  20. #define simplequeue_get_state_by_type(type) \
  21. (simplequeue_get_state(PyType_GetModuleByDef(type, &queuemodule)))
  22. typedef struct {
  23. PyObject_HEAD
  24. PyThread_type_lock lock;
  25. int locked;
  26. PyObject *lst;
  27. Py_ssize_t lst_pos;
  28. PyObject *weakreflist;
  29. } simplequeueobject;
  30. /*[clinic input]
  31. module _queue
  32. class _queue.SimpleQueue "simplequeueobject *" "simplequeue_get_state_by_type(type)->SimpleQueueType"
  33. [clinic start generated code]*/
  34. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=0a4023fe4d198c8d]*/
  35. static int
  36. simplequeue_clear(simplequeueobject *self)
  37. {
  38. Py_CLEAR(self->lst);
  39. return 0;
  40. }
  41. static void
  42. simplequeue_dealloc(simplequeueobject *self)
  43. {
  44. PyTypeObject *tp = Py_TYPE(self);
  45. PyObject_GC_UnTrack(self);
  46. if (self->lock != NULL) {
  47. /* Unlock the lock so it's safe to free it */
  48. if (self->locked > 0)
  49. PyThread_release_lock(self->lock);
  50. PyThread_free_lock(self->lock);
  51. }
  52. (void)simplequeue_clear(self);
  53. if (self->weakreflist != NULL)
  54. PyObject_ClearWeakRefs((PyObject *) self);
  55. Py_TYPE(self)->tp_free(self);
  56. Py_DECREF(tp);
  57. }
  58. static int
  59. simplequeue_traverse(simplequeueobject *self, visitproc visit, void *arg)
  60. {
  61. Py_VISIT(self->lst);
  62. Py_VISIT(Py_TYPE(self));
  63. return 0;
  64. }
  65. /*[clinic input]
  66. @classmethod
  67. _queue.SimpleQueue.__new__ as simplequeue_new
  68. Simple, unbounded, reentrant FIFO queue.
  69. [clinic start generated code]*/
  70. static PyObject *
  71. simplequeue_new_impl(PyTypeObject *type)
  72. /*[clinic end generated code: output=ba97740608ba31cd input=a0674a1643e3e2fb]*/
  73. {
  74. simplequeueobject *self;
  75. self = (simplequeueobject *) type->tp_alloc(type, 0);
  76. if (self != NULL) {
  77. self->weakreflist = NULL;
  78. self->lst = PyList_New(0);
  79. self->lock = PyThread_allocate_lock();
  80. self->lst_pos = 0;
  81. if (self->lock == NULL) {
  82. Py_DECREF(self);
  83. PyErr_SetString(PyExc_MemoryError, "can't allocate lock");
  84. return NULL;
  85. }
  86. if (self->lst == NULL) {
  87. Py_DECREF(self);
  88. return NULL;
  89. }
  90. }
  91. return (PyObject *) self;
  92. }
  93. /*[clinic input]
  94. _queue.SimpleQueue.put
  95. item: object
  96. block: bool = True
  97. timeout: object = None
  98. Put the item on the queue.
  99. The optional 'block' and 'timeout' arguments are ignored, as this method
  100. never blocks. They are provided for compatibility with the Queue class.
  101. [clinic start generated code]*/
  102. static PyObject *
  103. _queue_SimpleQueue_put_impl(simplequeueobject *self, PyObject *item,
  104. int block, PyObject *timeout)
  105. /*[clinic end generated code: output=4333136e88f90d8b input=6e601fa707a782d5]*/
  106. {
  107. /* BEGIN GIL-protected critical section */
  108. if (PyList_Append(self->lst, item) < 0)
  109. return NULL;
  110. if (self->locked) {
  111. /* A get() may be waiting, wake it up */
  112. self->locked = 0;
  113. PyThread_release_lock(self->lock);
  114. }
  115. /* END GIL-protected critical section */
  116. Py_RETURN_NONE;
  117. }
  118. /*[clinic input]
  119. _queue.SimpleQueue.put_nowait
  120. item: object
  121. Put an item into the queue without blocking.
  122. This is exactly equivalent to `put(item)` and is only provided
  123. for compatibility with the Queue class.
  124. [clinic start generated code]*/
  125. static PyObject *
  126. _queue_SimpleQueue_put_nowait_impl(simplequeueobject *self, PyObject *item)
  127. /*[clinic end generated code: output=0990536715efb1f1 input=36b1ea96756b2ece]*/
  128. {
  129. return _queue_SimpleQueue_put_impl(self, item, 0, Py_None);
  130. }
  131. static PyObject *
  132. simplequeue_pop_item(simplequeueobject *self)
  133. {
  134. Py_ssize_t count, n;
  135. PyObject *item;
  136. n = PyList_GET_SIZE(self->lst);
  137. assert(self->lst_pos < n);
  138. item = PyList_GET_ITEM(self->lst, self->lst_pos);
  139. Py_INCREF(Py_None);
  140. PyList_SET_ITEM(self->lst, self->lst_pos, Py_None);
  141. self->lst_pos += 1;
  142. count = n - self->lst_pos;
  143. if (self->lst_pos > count) {
  144. /* The list is more than 50% empty, reclaim space at the beginning */
  145. if (PyList_SetSlice(self->lst, 0, self->lst_pos, NULL)) {
  146. /* Undo pop */
  147. self->lst_pos -= 1;
  148. PyList_SET_ITEM(self->lst, self->lst_pos, item);
  149. return NULL;
  150. }
  151. self->lst_pos = 0;
  152. }
  153. return item;
  154. }
  155. /*[clinic input]
  156. _queue.SimpleQueue.get
  157. cls: defining_class
  158. /
  159. block: bool = True
  160. timeout as timeout_obj: object = None
  161. Remove and return an item from the queue.
  162. If optional args 'block' is true and 'timeout' is None (the default),
  163. block if necessary until an item is available. If 'timeout' is
  164. a non-negative number, it blocks at most 'timeout' seconds and raises
  165. the Empty exception if no item was available within that time.
  166. Otherwise ('block' is false), return an item if one is immediately
  167. available, else raise the Empty exception ('timeout' is ignored
  168. in that case).
  169. [clinic start generated code]*/
  170. static PyObject *
  171. _queue_SimpleQueue_get_impl(simplequeueobject *self, PyTypeObject *cls,
  172. int block, PyObject *timeout_obj)
  173. /*[clinic end generated code: output=5c2cca914cd1e55b input=5b4047bfbc645ec1]*/
  174. {
  175. _PyTime_t endtime = 0;
  176. _PyTime_t timeout;
  177. PyObject *item;
  178. PyLockStatus r;
  179. PY_TIMEOUT_T microseconds;
  180. PyThreadState *tstate = PyThreadState_Get();
  181. if (block == 0) {
  182. /* Non-blocking */
  183. microseconds = 0;
  184. }
  185. else if (timeout_obj != Py_None) {
  186. /* With timeout */
  187. if (_PyTime_FromSecondsObject(&timeout,
  188. timeout_obj, _PyTime_ROUND_CEILING) < 0) {
  189. return NULL;
  190. }
  191. if (timeout < 0) {
  192. PyErr_SetString(PyExc_ValueError,
  193. "'timeout' must be a non-negative number");
  194. return NULL;
  195. }
  196. microseconds = _PyTime_AsMicroseconds(timeout,
  197. _PyTime_ROUND_CEILING);
  198. if (microseconds > PY_TIMEOUT_MAX) {
  199. PyErr_SetString(PyExc_OverflowError,
  200. "timeout value is too large");
  201. return NULL;
  202. }
  203. endtime = _PyDeadline_Init(timeout);
  204. }
  205. else {
  206. /* Infinitely blocking */
  207. microseconds = -1;
  208. }
  209. /* put() signals the queue to be non-empty by releasing the lock.
  210. * So we simply try to acquire the lock in a loop, until the condition
  211. * (queue non-empty) becomes true.
  212. */
  213. while (self->lst_pos == PyList_GET_SIZE(self->lst)) {
  214. /* First a simple non-blocking try without releasing the GIL */
  215. r = PyThread_acquire_lock_timed(self->lock, 0, 0);
  216. if (r == PY_LOCK_FAILURE && microseconds != 0) {
  217. Py_BEGIN_ALLOW_THREADS
  218. r = PyThread_acquire_lock_timed(self->lock, microseconds, 1);
  219. Py_END_ALLOW_THREADS
  220. }
  221. if (r == PY_LOCK_INTR && _PyEval_MakePendingCalls(tstate) < 0) {
  222. return NULL;
  223. }
  224. if (r == PY_LOCK_FAILURE) {
  225. PyObject *module = PyType_GetModule(cls);
  226. simplequeue_state *state = simplequeue_get_state(module);
  227. /* Timed out */
  228. PyErr_SetNone(state->EmptyError);
  229. return NULL;
  230. }
  231. self->locked = 1;
  232. /* Adjust timeout for next iteration (if any) */
  233. if (microseconds > 0) {
  234. timeout = _PyDeadline_Get(endtime);
  235. microseconds = _PyTime_AsMicroseconds(timeout,
  236. _PyTime_ROUND_CEILING);
  237. }
  238. }
  239. /* BEGIN GIL-protected critical section */
  240. assert(self->lst_pos < PyList_GET_SIZE(self->lst));
  241. item = simplequeue_pop_item(self);
  242. if (self->locked) {
  243. PyThread_release_lock(self->lock);
  244. self->locked = 0;
  245. }
  246. /* END GIL-protected critical section */
  247. return item;
  248. }
  249. /*[clinic input]
  250. _queue.SimpleQueue.get_nowait
  251. cls: defining_class
  252. /
  253. Remove and return an item from the queue without blocking.
  254. Only get an item if one is immediately available. Otherwise
  255. raise the Empty exception.
  256. [clinic start generated code]*/
  257. static PyObject *
  258. _queue_SimpleQueue_get_nowait_impl(simplequeueobject *self,
  259. PyTypeObject *cls)
  260. /*[clinic end generated code: output=620c58e2750f8b8a input=842f732bf04216d3]*/
  261. {
  262. return _queue_SimpleQueue_get_impl(self, cls, 0, Py_None);
  263. }
  264. /*[clinic input]
  265. _queue.SimpleQueue.empty -> bool
  266. Return True if the queue is empty, False otherwise (not reliable!).
  267. [clinic start generated code]*/
  268. static int
  269. _queue_SimpleQueue_empty_impl(simplequeueobject *self)
  270. /*[clinic end generated code: output=1a02a1b87c0ef838 input=1a98431c45fd66f9]*/
  271. {
  272. return self->lst_pos == PyList_GET_SIZE(self->lst);
  273. }
  274. /*[clinic input]
  275. _queue.SimpleQueue.qsize -> Py_ssize_t
  276. Return the approximate size of the queue (not reliable!).
  277. [clinic start generated code]*/
  278. static Py_ssize_t
  279. _queue_SimpleQueue_qsize_impl(simplequeueobject *self)
  280. /*[clinic end generated code: output=f9dcd9d0a90e121e input=7a74852b407868a1]*/
  281. {
  282. return PyList_GET_SIZE(self->lst) - self->lst_pos;
  283. }
  284. static int
  285. queue_traverse(PyObject *m, visitproc visit, void *arg)
  286. {
  287. simplequeue_state *state = simplequeue_get_state(m);
  288. Py_VISIT(state->SimpleQueueType);
  289. Py_VISIT(state->EmptyError);
  290. return 0;
  291. }
  292. static int
  293. queue_clear(PyObject *m)
  294. {
  295. simplequeue_state *state = simplequeue_get_state(m);
  296. Py_CLEAR(state->SimpleQueueType);
  297. Py_CLEAR(state->EmptyError);
  298. return 0;
  299. }
  300. static void
  301. queue_free(void *m)
  302. {
  303. queue_clear((PyObject *)m);
  304. }
  305. #include "clinic/_queuemodule.c.h"
  306. static PyMethodDef simplequeue_methods[] = {
  307. _QUEUE_SIMPLEQUEUE_EMPTY_METHODDEF
  308. _QUEUE_SIMPLEQUEUE_GET_METHODDEF
  309. _QUEUE_SIMPLEQUEUE_GET_NOWAIT_METHODDEF
  310. _QUEUE_SIMPLEQUEUE_PUT_METHODDEF
  311. _QUEUE_SIMPLEQUEUE_PUT_NOWAIT_METHODDEF
  312. _QUEUE_SIMPLEQUEUE_QSIZE_METHODDEF
  313. {"__class_getitem__", Py_GenericAlias,
  314. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  315. {NULL, NULL} /* sentinel */
  316. };
  317. static struct PyMemberDef simplequeue_members[] = {
  318. {"__weaklistoffset__", T_PYSSIZET, offsetof(simplequeueobject, weakreflist), READONLY},
  319. {NULL},
  320. };
  321. static PyType_Slot simplequeue_slots[] = {
  322. {Py_tp_dealloc, simplequeue_dealloc},
  323. {Py_tp_doc, (void *)simplequeue_new__doc__},
  324. {Py_tp_traverse, simplequeue_traverse},
  325. {Py_tp_clear, simplequeue_clear},
  326. {Py_tp_members, simplequeue_members},
  327. {Py_tp_methods, simplequeue_methods},
  328. {Py_tp_new, simplequeue_new},
  329. {0, NULL},
  330. };
  331. static PyType_Spec simplequeue_spec = {
  332. .name = "_queue.SimpleQueue",
  333. .basicsize = sizeof(simplequeueobject),
  334. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  335. Py_TPFLAGS_IMMUTABLETYPE),
  336. .slots = simplequeue_slots,
  337. };
  338. /* Initialization function */
  339. PyDoc_STRVAR(queue_module_doc,
  340. "C implementation of the Python queue module.\n\
  341. This module is an implementation detail, please do not use it directly.");
  342. static int
  343. queuemodule_exec(PyObject *module)
  344. {
  345. simplequeue_state *state = simplequeue_get_state(module);
  346. state->EmptyError = PyErr_NewExceptionWithDoc(
  347. "_queue.Empty",
  348. "Exception raised by Queue.get(block=0)/get_nowait().",
  349. NULL, NULL);
  350. if (state->EmptyError == NULL) {
  351. return -1;
  352. }
  353. if (PyModule_AddObjectRef(module, "Empty", state->EmptyError) < 0) {
  354. return -1;
  355. }
  356. state->SimpleQueueType = (PyTypeObject *)PyType_FromModuleAndSpec(
  357. module, &simplequeue_spec, NULL);
  358. if (state->SimpleQueueType == NULL) {
  359. return -1;
  360. }
  361. if (PyModule_AddType(module, state->SimpleQueueType) < 0) {
  362. return -1;
  363. }
  364. return 0;
  365. }
  366. static PyModuleDef_Slot queuemodule_slots[] = {
  367. {Py_mod_exec, queuemodule_exec},
  368. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  369. {0, NULL}
  370. };
  371. static struct PyModuleDef queuemodule = {
  372. .m_base = PyModuleDef_HEAD_INIT,
  373. .m_name = "_queue",
  374. .m_doc = queue_module_doc,
  375. .m_size = sizeof(simplequeue_state),
  376. .m_slots = queuemodule_slots,
  377. .m_traverse = queue_traverse,
  378. .m_clear = queue_clear,
  379. .m_free = queue_free,
  380. };
  381. PyMODINIT_FUNC
  382. PyInit__queue(void)
  383. {
  384. return PyModuleDef_Init(&queuemodule);
  385. }