我在 C++ 中使用多线程 PythonQT。在不同线程中使用同名
值时,我想使用不同的值。
请帮帮我...
[代码:运行多线程]
int nRet = PyEval_ThreadsInitialized();
if (Py_IsInitialized() == 0)
{
Py_Initialize();
PyEval_InitThreads();
m_pyMainThread = PyEval_SaveThread();
}
std::shared_ptr<PythonWorkerThread> pythonWorker1 = std::make_shared<PythonWorkerThread>();
std::shared_ptr<PythonWorkerThread> pythonWorker2 = std::make_shared<PythonWorkerThread>();
pythonWorker1->setObjectName("1");
pythonWorker2->setObjectName("2");
pythonWorker1->start();
pythonWorker2->start();
[代码:运行 WorkerThread]
void PythonWorkerThread::run()
{
qDebug() << "Thread Run = " << objectName() << " ThreadID = " << (int)QThread::currentThreadId();
auto state = PyGILState_Ensure();
for (int i = 0; i < 10; ++i)
{
PythonQt::self()->addVariable(PythonQt::self()->getMainModule(), "SharedValue", i);
QString strScrip = QString("import time\n" "time.sleep(%1)\n").arg(objectName().toInt());
PyRun_SimpleString(strScrip.toStdString().c_str());
qDebug() << "Thread = " << objectName() << ", i =" << i << PythonQt::self()->getMainModule().getVariable("SharedValue");
}
PyGILState_Release(state);
qDebug() << "Thread End" << objectName();
}
[结果:粗体是不正确的值]
线程运行 = "1"
线程 ID = 25884 线程运行 = "2" 线程 ID = 21848
线程 = "1", i = 0 QVariant(int, 0)
线程 = "2", i = 0 QVariant(int, 1)
线程 = "1", i = 1 QVariant(int, 1)
线程 = "1", i = 2 QVariant(int, 2)
线程 = "2", i = 1 QVariant(int, 3)
线程 = "1", i = 3 QVariant(int, 2)
线程 = "1", i = 4 QVariant(int, 4)
线程 = "2", i = 2 QVariant(int, 5)
线程 = "1", i = 5 QVariant(int , 3)
线程 = "1", i = 6 QVariant(int, 6)
线程 = "2", i = 3 QVariant(int, 7)
线程 = "1", i = 7 QVariant(int, 4)
线程 = "1", i = 8 QVariant(int,8)
线程 = "2", i = 4 QVariant(int, 9)
线程 = "1", i = 9 QVariant(int, 5)
线程结束“1”
线程 0x651c 已退出,代码为 0 (0x0)。
线程 = "2", i = 5 QVariant(int, 5)
线程 = "2", i = 6 QVariant(int, 6)
线程 = "2", i = 7 QVariant(int, 7)
线程 = "2" , i = 8 QVariant(int, 8)
Thread = "2", i = 9 QVariant(int, 9)
Thread End "2"
线程 0x5558 已退出,代码为 0 (0x0)。