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的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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 ) |
好了,结束了,其中的安装,需要自己百度。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述