Skip to content

[QUESTION] Something confusing when I import the library from a std::thread in c++ #3057

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
z-pc opened this issue Jun 24, 2021 · 1 comment

Comments

@z-pc
Copy link

z-pc commented Jun 24, 2021

I want to call some functions in Python by C++ program. This is my sample:
"testmain.cpp"

// Example program
#include <iostream>
#include <fstream>
#include <utility>
#include <thread>
#include "pybind11/embed.h"
#include "pybind11/stl.h"

namespace py = pybind11;

static void TestThread(const char* path)
{
	py::module_ sys__ = py::module_::import("sys");
	std::cout << "import sys success" << std::endl;
	py::module_ cv2 = py::module_::import("cv2"); //-> 1. This line confuses me
	std::cout << "preparing imread" << std::endl;
	cv2.attr("imread")(path);
	std::cout << "imread success" << std::endl;
}

int main(int argc, const char** argv) 
{
	pybind11::scoped_interpreter guard{};
	{
		try
		{
			//py::module_::import("cv2");  //-> 2. This line confuses me
			std::string path("G:/ocr6DD1.tmp");
			std::thread th(TestThread, path.c_str());

			if (th.joinable())
				th.join();
		}
		catch (const pybind11::error_already_set& e)
		{
			std::cout << e.what() << std::endl;
		}
		catch (const std::exception& e)
		{
			std::cout << e.what() << std::endl;
		}
		catch (const std::runtime_error& e)
		{
			std::cout << e.what() << std::endl;
		}

	}
	return 1;
}

In my local, when running the thread to this line

py::module_ cv2 = py::module_::import("cv2"); //-> 1. This line confuses me

The program is suspended indefinitely, but If I uncomment this line

//py::module_::import("cv2");  //-> 2. This line confuses me

the thread will passing that import opencv.
I'm just learning about pybind11 and the interpreter, looking forward to a detailed answer.

Information:
Win10 x64
Visual Studio 2019 Enterprise
Opencv-python 4.5.2.54

@z-pc
Copy link
Author

z-pc commented Jun 24, 2021

I found an answer in this #1273

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant