File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 1010#include " pybind11_tests.h"
1111#include " constructor_stats.h"
1212#include < pybind11/functional.h>
13+ #include < thread>
1314
1415
1516int dummy_function (int i) { return i + 1 ; }
@@ -146,4 +147,21 @@ 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 t = std::thread ([f = std::move (f), j] {
157+ std::this_thread::sleep_for (std::chrono::milliseconds (50 ));
158+ f (j);
159+ });
160+ t.detach ();
161+ };
162+
163+ // spawn worker threads
164+ for (auto i : work)
165+ start_f (py::cast<int >(i));
166+ });
149167}
Original file line number Diff line number Diff line change @@ -105,3 +105,24 @@ def test_function_signatures(doc):
105105
106106def 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+ # generate stateful lambda that will store result in `res`
117+ res = []
118+ def gen_f ():
119+ I = item (3 )
120+ return lambda j : res .append (I .value + j )
121+
122+ # do some work async
123+ work = [1 , 2 , 3 , 4 ]
124+ m .test_async_callback (gen_f (), work )
125+ # wait until work is done
126+ from time import sleep
127+ sleep (0.5 )
128+ assert sum (res ) == sum ([x + 3 for x in work ])
You can’t perform that action at this time.
0 commit comments