File tree 2 files changed +39
-0
lines changed
2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 10
10
#include " pybind11_tests.h"
11
11
#include " constructor_stats.h"
12
12
#include < pybind11/functional.h>
13
+ #include < thread>
13
14
14
15
15
16
int dummy_function (int i) { return i + 1 ; }
@@ -146,4 +147,21 @@ TEST_SUBMODULE(callbacks, m) {
146
147
py::class_<CppBoundMethodTest>(m, " CppBoundMethodTest" )
147
148
.def (py::init<>())
148
149
.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
+ });
149
167
}
Original file line number Diff line number Diff line change @@ -105,3 +105,24 @@ def test_function_signatures(doc):
105
105
106
106
def test_movable_object ():
107
107
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