I am using multithreading PythonQT in C++.
When using values of the same name in different threads, I want to use different values.
Help me plz...

[Code : run multithreading]

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();

[Code : run 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();
}



[Result : Bold is incorrect value]

Thread Run = "1" ThreadID = 25884
Thread Run = "2" ThreadID = 21848
Thread = "1", i = 0 QVariant(int, 0)
Thread = "2", i = 0 QVariant(int, 1)
Thread = "1", i = 1 QVariant(int, 1)
Thread = "1", i = 2 QVariant(int, 2)
Thread = "2", i = 1 QVariant(int, 3)
Thread = "1", i = 3 QVariant(int, 2)
Thread = "1", i = 4 QVariant(int, 4)
Thread = "2", i = 2 QVariant(int, 5)
Thread = "1", i = 5 QVariant(int, 3)
Thread = "1", i = 6 QVariant(int, 6)
Thread = "2", i = 3 QVariant(int, 7)
Thread = "1", i = 7 QVariant(int, 4)
Thread = "1", i = 8 QVariant(int, 8)
Thread = "2", i = 4 QVariant(int, 9)
Thread = "1", i = 9 QVariant(int, 5)
Thread End "1"
The thread 0x651c has exited with code 0 (0x0).
Thread = "2", i = 5 QVariant(int, 5)
Thread = "2", i = 6 QVariant(int, 6)
Thread = "2", i = 7 QVariant(int, 7)
Thread = "2", i = 8 QVariant(int, 8)
Thread = "2", i = 9 QVariant(int, 9)
Thread End "2"
The thread 0x5558 has exited with code 0 (0x0).

0

There are 0 answers