Пытаюсь из кода на python, распараллеленного с помощью ThreadPoolExecutor вызвать код на C++. Создается впечатление, что в момент входа в C++ функцию все питоновские потоки замораживаются. Пример:
#include <boost/python.hpp>
#include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>
using namespace std;
using namespace std::chrono;
using namespace std::this_thread;
using namespace boost::python;
void foo(int i)
{
cout<<"Enter " << " foo("<<i<<") (c++) thread: " << get_id() << endl;
sleep_for( seconds(2) );
cout<<"Exit " << " foo("<<i<<") (c++) thread: " << get_id() << endl;
}
BOOST_PYTHON_MODULE( test_py_async )
{
def("foo", &foo);
}
python:
import test_py_async
import concurrent.futures
N=8
def foo(i):
print( f"Enter foo({i}) (py)")
test_py_async.foo(i)
print( f"Exit foo({i}) (py)")
return i
with concurrent.futures.ThreadPoolExecutor(max_workers=N) as executor:
print("submit tasks:")
futures=[ executor.submit( foo, i ) for i in range(N) ]
print("wait for tasks:")
results=[ future.result() for future in futures ]
print(f"results: {results}")
print(f"exit ThreadPoolExecutor")
assert( results == [ i for i in range(N) ] )
вывод:
submit tasks:
Enter foo(0) (py)
Enter foo(0) (c++) thread: 11796
Exit foo(0) (c++) thread: 11796
Enter foo(1) (py)
Enter foo(1) (c++) thread: 16580
Exit foo(1) (c++) thread: 16580
Exit foo(0) (py)
Enter foo(2) (py)
Enter foo(2) (c++) thread: 20240
Exit foo(2) (c++) thread: 20240
Enter foo(3) (py)
Exit foo(1) (py)
Enter foo(3) (c++) thread: 11796
Exit foo(3) (c++) thread: 11796
Exit foo(2) (py)
Enter foo(4) (py)
Enter foo(4) (c++) thread: 17568
Exit foo(4) (c++) thread: 17568
Enter foo(6) (py)
Enter foo(6) (c++) thread: 19672
Exit foo(6) (c++) thread: 19672
Enter foo(5) (py)
Enter foo(7) (py)
Enter foo(7) (c++) thread: 16580
Exit foo(7) (c++) thread: 16580
wait for tasks:
Exit foo(3) (py)
Exit foo(6) (py)
Exit foo(7) (py)
Exit foo(4) (py)
Exit foo(5) (c++) thread: 16804
Exit foo(5) (py)
results: [0, 1, 2, 3, 4, 5, 6, 7]
exit ThreadPoolExecutor
Из лога видно, что вызовы c++ не пересекаются по времени выполнения ни с другими вызовами c++ , ни с питоновским кодом, хотя вызовы действительно производятся из разных потоков. Что я делаю нетак?