我想从QtScript脚本运行几个并发作业:
function job1() { ... }
function job2() { ... }
runConcurrentJobs(job1, job2)
作业本质上是一系列远程过程调用(ZeroC Ice),需要在多个点进行同步。
Qt 4.8.0文档没有说明QScriptEngine
线程安全性。我的问题:
使用单个
QScriptEngine
同时从多个线程执行QtScript函数是否安全?你建议用什么方法来完成任务?
注意:
- 脚本不是由程序员编辑的,也由电气工程师编辑,我想让脚本尽可能简单干净
QScriptEngine
被记录为"可重入",这意味着,本质上,您可以多线程使用它,但每个线程只能使用一个QScriptEngine
。
现在,如果函数job1()
和job2()
可以同时运行,原则上,应该可以将它们分离为两个不同的QScriptEngine
(如果两个函数都不使用局部变量,则很容易,如果涉及全局变量,则更困难)。
- 在C++中将
runConcurrentJobs()
实现为Q_INVOKABLE
函数(或槽) -
在那里,做一些类似的事情
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 }
-
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 }
-
一般来说,如果文档中没有提到线程,那么它就不是线程安全的。
-
我会重写以使用异步请求。把他们两个踢开,然后等他们两个。