Skip to content

Commit bdc79fc

Browse files
committed
Add test case for async Python stateful callbacks
1 parent e9d6e87 commit bdc79fc

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

tests/test_callbacks.cpp

+19
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include "pybind11_tests.h"
1111
#include "constructor_stats.h"
1212
#include <pybind11/functional.h>
13+
#include <thread>
1314

1415

1516
int dummy_function(int i) { return i + 1; }
@@ -146,4 +147,22 @@ TEST_SUBMODULE(callbacks, m) {
146147
py::class_<CppBoundMethodTest>(m, "CppBoundMethodTest")
147148
.def(py::init<>())
148149
.def("triple", [](CppBoundMethodTest &, int val) { return 3 * val; });
150+
151+
// test async Python callbacks
152+
using callback_f = std::function<void(int)>;
153+
m.def("test_async_callback", [](callback_f f, py::list work) {
154+
// make detached thread that calls `f` with piece of work after a little delay
155+
auto start_f = [f](int j) {
156+
auto invoke_f = [f, j] {
157+
std::this_thread::sleep_for(std::chrono::milliseconds(50));
158+
f(j);
159+
};
160+
auto t = std::thread(std::move(invoke_f));
161+
t.detach();
162+
};
163+
164+
// spawn worker threads
165+
for (auto i : work)
166+
start_f(py::cast<int>(i));
167+
});
149168
}

tests/test_callbacks.py

+22
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,25 @@ def test_function_signatures(doc):
105105

106106
def test_movable_object():
107107
assert m.callback_with_movable(lambda _: None) is True
108+
109+
110+
def test_async_callbacks():
111+
# serves as state for async callback
112+
class Item:
113+
def __init__(self, value):
114+
self.value = value
115+
116+
res = []
117+
118+
# generate stateful lambda that will store result in `res`
119+
def gen_f():
120+
s = Item(3)
121+
return lambda j: res.append(s.value + j)
122+
123+
# do some work async
124+
work = [1, 2, 3, 4]
125+
m.test_async_callback(gen_f(), work)
126+
# wait until work is done
127+
from time import sleep
128+
sleep(0.5)
129+
assert sum(res) == sum([x + 3 for x in work])

0 commit comments

Comments
 (0)