c++多线程和python多线程相互调用(c++线程一直给python推数据)
先看c++代码,很多代码不懂,能百度到的
#define EXPORT __declspec(dllexport) #include <iostream> #include <pthread.h> #include<Python.h> #include <windows.h> using namespace std; pthread_t tids[1]; PyObject* pModule = NULL;//声明变量 void* say_hello(void* args) { PyObject* pFunc = NULL;// 声明变量 pFunc = PyObject_GetAttrString(pModule, "add"); while (true) { int a = rand() % 100; PyGILState_STATE state = PyGILState_Ensure(); PyObject* args = Py_BuildValue("(i)", a);//给python函数参数赋值 PyObject* pRet = PyObject_CallObject(pFunc, args); PyGILState_Release(state); Sleep(500); } Py_Finalize(); } class TestLib { public: void display(); void init_(); }; void TestLib::display() { pthread_create(&tids[0], NULL, say_hello, NULL); } void TestLib::init_() { Py_SetPythonHome(L"C:/Users/ccy/Anaconda3"); Py_Initialize(); PyEval_InitThreads(); PyGILState_STATE state = PyGILState_Ensure(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); pModule = PyImport_ImportModule("cpy"); PyGILState_Release(state); } extern "C" { TestLib obj; EXPORT void display() { obj.display(); } EXPORT void init_() { obj.init_(); } }
首先 pthread.h的安装可以参考这个网址
https://blog.csdn.net/ZPeng_CSDN/article/details/114108421
TestLib::init_() 里面的内容不能放在线程里面 去 init,否则程序运行不起来,要先init,再运行线程
线程里面运行的python代码,必须用
PyGILState_STATE state = PyGILState_Ensure();
这些,否则python的机制不允许,会自动停下来
至于
python的代码:
import ctypes
import time
from threading import Thread
lib=ctypes.CDLL(r"./cpyth1.dll")
lib.init_()
lib.display()
class baseEntity():
a=0
def __init__(self) -> None:
pass
def set_a(self,a):
self.a=a
def get_a(self):
return self.a
bentity=baseEntity()
def add(a):
bentity.set_a(int(a))
while 1:
print(bentity.get_a())
time.sleep(1)
好了,结束了,其中的安装,需要自己百度。
浙公网安备 33010602011771号