我想从 QtScript 脚本运行多个并发作业:
function job1() { ... }
function job2() { ... }
runConcurrentJobs(job1, job2)
作业本质上是一系列远程过程调用 (ZeroC Ice),需要在多个点进行同步。
Qt 4.8.0 文档没有提及QScriptEngine
线程安全。我的问题:
使用单个
QScriptEngine
从多个线程同时执行 QtScript 函数是否安全?您会推荐什么方法来完成任务?
注意事项:
- 脚本不是由程序员编辑的,也是由电气工程师编辑的,我希望脚本尽可能简单明了。
最佳答案
QScriptEngine
被记录为“可重入”,这意味着,本质上,您可以在多线程中使用它,但每个线程只能使用一个 QScriptEngine
。
现在,如果函数 job1()
和 job2()
可以同时运行,原则上应该可以将它们分成两个不同的 QScriptEngine
s(简单,如果两个函数都不使用局部变量,只有,更难,如果涉及全局变量)。
- 在 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 }
关于c++ - QtScript 和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8893571/