QtScript and threads

QtScript and threads

本文关键字:threads and QtScript      更新时间:2023-10-16

我想从QtScript脚本运行几个并发作业:

function job1() { ... }
function job2() { ... }
runConcurrentJobs(job1, job2)

作业本质上是一系列远程过程调用(ZeroC Ice),需要在多个点进行同步。

Qt 4.8.0文档没有说明QScriptEngine线程安全性。我的问题:

  1. 使用单个QScriptEngine同时从多个线程执行QtScript函数是否安全?

  2. 你建议用什么方法来完成任务?

注意:

  1. 脚本不是由程序员编辑的,也由电气工程师编辑,我想让脚本尽可能简单干净

QScriptEngine被记录为"可重入",这意味着,本质上,您可以多线程使用它,但每个线程只能使用一个QScriptEngine

现在,如果函数job1()job2()可以同时运行,原则上,应该可以将它们分离为两个不同的QScriptEngine(如果两个函数都不使用局部变量,则很容易,如果涉及全局变量,则更困难)。

  1. 在C++中将runConcurrentJobs()实现为Q_INVOKABLE函数(或槽)
  2. 在那里,做一些类似的事情

       void runConcurrently (const QString &functionname1, QString &functionname2) {
           MyScriptThread thread1 (functionname1);
           MyScriptThread thread2 (functionname2);
           thread1.start();
           thread2.start();
           thread1.wait ();
           thread2.wait ();
           // optionally fetch return values from the threads and return them
       }
    
  3. MyScriptThread从QThread派生,并实现QThread::run(),大致如下:

       void MyScriptThread::run () {
             QScriptEngine engine;
             engine.evaluate (common_script_code);
             result = engine.evaluate (the_threads_function);
             // the_threads_function passed as a QScriptProgram or QString
       }
    
  1. 一般来说,如果文档中没有提到线程,那么它就不是线程安全的。

  2. 我会重写以使用异步请求。把他们两个踢开,然后等他们两个。