Skip to content

Commit

Permalink
Add RingBuf APIs for empty/length
Browse files Browse the repository at this point in the history
To help reduce future churn.
  • Loading branch information
mpage committed Jan 19, 2024
1 parent 7e54296 commit 49956aa
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions Modules/_queuemodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "pycore_moduleobject.h" // _PyModule_GetState()
#include "pycore_time.h" // _PyTime_t

#include <stdbool.h>
#include <stddef.h> // offsetof()

typedef struct {
Expand Down Expand Up @@ -169,6 +170,18 @@ RingBuf_Put(RingBuf *buf, PyObject *item)
return 0;
}

static Py_ssize_t
RingBuf_Len(RingBuf *buf)
{
return buf->num_items;
}

static bool
RingBuf_IsEmpty(RingBuf *buf)
{
return RingBuf_Len(buf) == 0;
}

typedef struct {
PyObject_HEAD
PyThread_type_lock lock;
Expand Down Expand Up @@ -366,7 +379,7 @@ _queue_SimpleQueue_get_impl(simplequeueobject *self, PyTypeObject *cls,
* So we simply try to acquire the lock in a loop, until the condition
* (queue non-empty) becomes true.
*/
while (self->buf.num_items == 0) {
while (RingBuf_IsEmpty(&self->buf)) {
/* First a simple non-blocking try without releasing the GIL */
r = PyThread_acquire_lock_timed(self->lock, 0, 0);
if (r == PY_LOCK_FAILURE && microseconds != 0) {
Expand Down Expand Up @@ -436,7 +449,7 @@ static int
_queue_SimpleQueue_empty_impl(simplequeueobject *self)
/*[clinic end generated code: output=1a02a1b87c0ef838 input=1a98431c45fd66f9]*/
{
return self->buf.num_items == 0;
return RingBuf_IsEmpty(&self->buf);
}

/*[clinic input]
Expand All @@ -449,7 +462,7 @@ static Py_ssize_t
_queue_SimpleQueue_qsize_impl(simplequeueobject *self)
/*[clinic end generated code: output=f9dcd9d0a90e121e input=7a74852b407868a1]*/
{
return self->buf.num_items;
return RingBuf_Len(&self->buf);
}

static int
Expand Down

0 comments on commit 49956aa

Please sign in to comment.