File tree 2 files changed +48
-0
lines changed
2 files changed +48
-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,22 @@ 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 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
+ });
149
168
}
Original file line number Diff line number Diff line change 1
1
import pytest
2
2
from pybind11_tests import callbacks as m
3
+ from threading import Thread
3
4
4
5
5
6
def test_callbacks ():
@@ -105,3 +106,31 @@ def test_function_signatures(doc):
105
106
106
107
def test_movable_object ():
107
108
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 ()
You can’t perform that action at this time.
0 commit comments