Skip to content

Commit 0273996

Browse files
committed
refactor(event-loop): add a wrapper function for every job function sent to the Python event-loop
1 parent 4b5cfab commit 0273996

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/PyEventLoop.cc

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,26 @@
22

33
#include <Python.h>
44

5+
static PyObject *eventLoopJobWrapper(PyObject *jobFn, PyObject *Py_UNUSED(_)) {
6+
PyObject *ret = PyObject_CallObject(jobFn, NULL); // jobFn()
7+
Py_XDECREF(ret); // don't care about its return value
8+
Py_RETURN_NONE;
9+
}
10+
static PyMethodDef jobWrapperDef = {"eventLoopJobWrapper", eventLoopJobWrapper, METH_NOARGS, NULL};
11+
512
PyEventLoop::AsyncHandle PyEventLoop::enqueue(PyObject *jobFn) {
13+
PyObject *wrapper = PyCFunction_New(&jobWrapperDef, jobFn);
614
// Enqueue job to the Python event-loop
715
// https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_soon
8-
PyObject *asyncHandle = PyObject_CallMethod(_loop, "call_soon_threadsafe", "O", jobFn); // https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue
16+
PyObject *asyncHandle = PyObject_CallMethod(_loop, "call_soon_threadsafe", "O", wrapper); // https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue
917
return PyEventLoop::AsyncHandle(asyncHandle);
1018
}
1119

1220
PyEventLoop::AsyncHandle PyEventLoop::enqueueWithDelay(PyObject *jobFn, double delaySeconds) {
21+
PyObject *wrapper = PyCFunction_New(&jobWrapperDef, jobFn);
1322
// Schedule job to the Python event-loop
1423
// https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_later
15-
PyObject *asyncHandle = PyObject_CallMethod(_loop, "call_later", "dO", delaySeconds, jobFn); // https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue
24+
PyObject *asyncHandle = PyObject_CallMethod(_loop, "call_later", "dO", delaySeconds, wrapper); // https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue
1625
if (asyncHandle == nullptr) {
1726
PyErr_Print(); // RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one
1827
}

0 commit comments

Comments
 (0)