Skip to content

Commit 83113a0

Browse files
committed
Add async Python callbacks test that runs in separate Python thread
1 parent e2b884c commit 83113a0

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-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

+29
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import pytest
22
from pybind11_tests import callbacks as m
3+
from threading import Thread
34

45

56
def test_callbacks():
@@ -105,3 +106,31 @@ def test_function_signatures(doc):
105106

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

0 commit comments

Comments
 (0)