Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:17:57

0001 /*
0002     tests/test_thread.cpp -- call pybind11 bound methods in threads
0003 
0004     Copyright (c) 2021 Laramie Leavitt (Google LLC) <lar@google.com>
0005 
0006     All rights reserved. Use of this source code is governed by a
0007     BSD-style license that can be found in the LICENSE file.
0008 */
0009 
0010 #include <pybind11/cast.h>
0011 #include <pybind11/pybind11.h>
0012 
0013 #include "pybind11_tests.h"
0014 
0015 #include <chrono>
0016 #include <thread>
0017 
0018 namespace py = pybind11;
0019 
0020 namespace {
0021 
0022 struct IntStruct {
0023     explicit IntStruct(int v) : value(v){};
0024     ~IntStruct() { value = -value; }
0025     IntStruct(const IntStruct &) = default;
0026     IntStruct &operator=(const IntStruct &) = default;
0027 
0028     int value;
0029 };
0030 
0031 } // namespace
0032 
0033 TEST_SUBMODULE(thread, m) {
0034 
0035     py::class_<IntStruct>(m, "IntStruct").def(py::init([](const int i) { return IntStruct(i); }));
0036 
0037     // implicitly_convertible uses loader_life_support when an implicit
0038     // conversion is required in order to lifetime extend the reference.
0039     //
0040     // This test should be run with ASAN for better effectiveness.
0041     py::implicitly_convertible<int, IntStruct>();
0042 
0043     m.def("test", [](int expected, const IntStruct &in) {
0044         {
0045             py::gil_scoped_release release;
0046             std::this_thread::sleep_for(std::chrono::milliseconds(5));
0047         }
0048 
0049         if (in.value != expected) {
0050             throw std::runtime_error("Value changed!!");
0051         }
0052     });
0053 
0054     m.def(
0055         "test_no_gil",
0056         [](int expected, const IntStruct &in) {
0057             std::this_thread::sleep_for(std::chrono::milliseconds(5));
0058             if (in.value != expected) {
0059                 throw std::runtime_error("Value changed!!");
0060             }
0061         },
0062         py::call_guard<py::gil_scoped_release>());
0063 
0064     // NOTE: std::string_view also uses loader_life_support to ensure that
0065     // the string contents remain alive, but that's a C++ 17 feature.
0066 }