forked from Distributive-Network/PythonMonkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyEventLoop.cc
More file actions
154 lines (129 loc) · 6.22 KB
/
PyEventLoop.cc
File metadata and controls
154 lines (129 loc) · 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include "include/PyEventLoop.hh"
#include <Python.h>
PyEventLoop::AsyncHandle PyEventLoop::enqueue(PyObject *jobFn) {
// Enqueue job to the Python event-loop
// https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_soon
PyObject *asyncHandle = PyObject_CallMethod(_loop, "call_soon_threadsafe", "O", jobFn); // https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue
return PyEventLoop::AsyncHandle(asyncHandle);
}
PyEventLoop::AsyncHandle PyEventLoop::enqueueWithDelay(PyObject *jobFn, double delaySeconds) {
// Schedule job to the Python event-loop
// https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_later
PyObject *asyncHandle = PyObject_CallMethod(_loop, "call_later", "dO", delaySeconds, jobFn); // https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue
if (asyncHandle == nullptr) {
PyErr_Print(); // RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one
}
return PyEventLoop::AsyncHandle(asyncHandle);
}
PyEventLoop::Future PyEventLoop::createFuture() {
// https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.create_future
PyObject *futureObj = PyObject_CallMethod(_loop, "create_future", NULL);
return PyEventLoop::Future(futureObj);
}
PyEventLoop::Future PyEventLoop::ensureFuture(PyObject *awaitable) {
PyObject *asyncio = PyImport_ImportModule("asyncio");
PyObject *ensure_future_fn = PyObject_GetAttrString(asyncio, "ensure_future"); // ensure_future_fn = asyncio.ensure_future
// instead of a simpler `PyObject_CallMethod`, only the `PyObject_Call` API function can be used here because `loop` is a keyword-only argument
// see https://docs.python.org/3.9/library/asyncio-future.html#asyncio.ensure_future
// https://docs.python.org/3/c-api/call.html#object-calling-api
PyObject *args = PyTuple_New(1);
PyTuple_SetItem(args, 0, awaitable);
PyObject *kwargs = PyDict_New();
PyDict_SetItemString(kwargs, "loop", _loop);
PyObject *futureObj = PyObject_Call(ensure_future_fn, args, kwargs); // futureObj = ensure_future_fn(awaitable, loop=_loop)
// clean up
Py_DECREF(asyncio);
Py_DECREF(ensure_future_fn);
Py_DECREF(args);
Py_DECREF(kwargs);
return PyEventLoop::Future(futureObj);
}
/* static */
PyEventLoop PyEventLoop::_loopNotFound() {
PyErr_SetString(PyExc_RuntimeError, "PythonMonkey cannot find a running Python event-loop to make asynchronous calls.");
return PyEventLoop(nullptr);
}
/* static */
PyEventLoop PyEventLoop::_getLoopOnThread(PyThreadState *tstate) {
// Modified from Python 3.9 `get_running_loop` https://github.com/python/cpython/blob/7cb3a44/Modules/_asynciomodule.c#L241-L278
PyObject *ts_dict = _PyThreadState_GetDict(tstate); // borrowed reference
if (ts_dict == NULL) {
return _loopNotFound();
}
// TODO: Python `get_running_loop` caches the PyRunningLoopHolder, should we do it as well for the main thread?
// see https://github.com/python/cpython/blob/7cb3a44/Modules/_asynciomodule.c#L234-L239
PyObject *rl = PyDict_GetItemString(ts_dict, "__asyncio_running_event_loop__"); // borrowed reference
if (rl == NULL) {
return _loopNotFound();
}
using PyRunningLoopHolder = struct {
PyObject_HEAD
PyObject *rl_loop;
};
PyObject *running_loop = ((PyRunningLoopHolder *)rl)->rl_loop;
if (running_loop == Py_None) {
return _loopNotFound();
}
Py_INCREF(running_loop);
return PyEventLoop(running_loop);
}
/* static */
PyThreadState *PyEventLoop::_getMainThread() {
// The last element in the linked-list of threads associated with the main interpreter should be the main thread
// (The first element is the current thread, see https://github.com/python/cpython/blob/7cb3a44/Python/pystate.c#L291-L293)
PyInterpreterState *interp = PyInterpreterState_Main();
PyThreadState *tstate = PyInterpreterState_ThreadHead(interp); // https://docs.python.org/3/c-api/init.html#c.PyInterpreterState_ThreadHead
while (PyThreadState_Next(tstate) != nullptr) {
tstate = PyThreadState_Next(tstate);
}
return tstate;
}
/* static inline */
PyThreadState *PyEventLoop::_getCurrentThread() {
// `PyThreadState_Get` is used under the hood of the Python `asyncio.get_running_loop` method,
// see https://github.com/python/cpython/blob/7cb3a44/Modules/_asynciomodule.c#L234
return PyThreadState_Get(); // https://docs.python.org/3/c-api/init.html#c.PyThreadState_Get
}
/* static */
PyEventLoop PyEventLoop::getMainLoop() {
return _getLoopOnThread(_getMainThread());
}
/* static */
PyEventLoop PyEventLoop::getRunningLoop() {
return _getLoopOnThread(_getCurrentThread());
}
void PyEventLoop::AsyncHandle::cancel() {
// https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.Handle.cancel
PyObject *ret = PyObject_CallMethod(_handle, "cancel", NULL); // returns None
Py_XDECREF(ret);
}
void PyEventLoop::Future::setResult(PyObject *result) {
// https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.set_result
PyObject *ret = PyObject_CallMethod(_future, "set_result", "O", result); // returns None
Py_XDECREF(ret);
}
void PyEventLoop::Future::setException(PyObject *exception) {
// https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.set_exception
PyObject *ret = PyObject_CallMethod(_future, "set_exception", "O", exception); // returns None
Py_XDECREF(ret);
}
void PyEventLoop::Future::addDoneCallback(PyObject *cb) {
// https://docs.python.org/3.9/library/asyncio-future.html#asyncio.Future.add_done_callback
PyObject *ret = PyObject_CallMethod(_future, "add_done_callback", "O", cb); // returns None
Py_XDECREF(ret);
}
bool PyEventLoop::Future::isCancelled() {
// https://docs.python.org/3.9/library/asyncio-future.html#asyncio.Future.cancelled
PyObject *ret = PyObject_CallMethod(_future, "cancelled", NULL); // returns Python bool
bool cancelled = ret == Py_True;
Py_XDECREF(ret);
return cancelled;
}
PyObject *PyEventLoop::Future::getResult() {
// https://docs.python.org/3.9/library/asyncio-future.html#asyncio.Future.result
return PyObject_CallMethod(_future, "result", NULL);
}
PyObject *PyEventLoop::Future::getException() {
// https://docs.python.org/3.9/library/asyncio-future.html#asyncio.Future.exception
return PyObject_CallMethod(_future, "exception", NULL);
}