Skip to content

Commit

Permalink
test: embed multiprocessing.Process can be created with spawn context
Browse files Browse the repository at this point in the history
  • Loading branch information
aaraney committed Jul 11, 2024
1 parent 50acb81 commit 18af993
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
3 changes: 2 additions & 1 deletion tests/test_embed/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ pybind11_enable_warnings(test_embed)
target_link_libraries(test_embed PRIVATE pybind11::embed Catch2::Catch2 Threads::Threads)

if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)
file(COPY test_interpreter.py test_trampoline.py DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
file(COPY test_interpreter.py test_trampoline.py test_multiprocessing.py
DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
endif()

add_custom_target(
Expand Down
9 changes: 9 additions & 0 deletions tests/test_embed/test_interpreter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -486,3 +486,12 @@ TEST_CASE("make_iterator can be called before then after finalizing an interpret

py::initialize_interpreter();
}

TEST_CASE("scoped_interpreter multiprocessing.Process can be created with spawn context") {
py::finalize_interpreter();
REQUIRE_NOTHROW([&]() {
py::scoped_interpreter default_scope;
py::module_::import("test_multiprocessing").attr("main")();
}());
py::initialize_interpreter();
}
29 changes: 29 additions & 0 deletions tests/test_embed/test_multiprocessing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from __future__ import annotations

import multiprocessing
import multiprocessing.connection


def f(tx: multiprocessing.connection.Connection, n: int):
tx.send(n**2)
tx.close()


def main():
multiprocessing.set_start_method("spawn")
assert multiprocessing.get_start_method() == "spawn", "expected spawn"

rx, tx = multiprocessing.Pipe()
proc = multiprocessing.Process(target=f, args=(tx, 5))
proc.start()

value: int | None = None
for _ in range(5):
if rx.poll(1.0):
value = rx.recv()
break
rx.close()
proc.join(1.0)

assert value is not None, "no data received"
assert value == 5**2, f"expected {5**2} got {value}"

0 comments on commit 18af993

Please sign in to comment.