简体   繁体   English

同时运行两个QThread

[英]Running two QThreads simultaneously

My goal for a task is to allow one button press to start two processes, both running simultaneously on different QThreads. 我的任务目标是允许按下一个按钮来启动两个进程,两个进程同时在不同的QThreads上运行。

My code is structured like this (simplified) 我的代码结构如下(简化)

class Main_Window():

    # My UI stuff goes here

class worker1(QtCore.QObject):
    def __init__(self):
        ...

    def run1():
        ...

class worker2(QtCore.QObject):
    def __init__(self):
        ...

    def run2():
        ...

app = QtGui.QApplication(sys.argv)
myapp = Main_Window()

thr1 = QtCore.QThread()
thr2 = QtCore.QThread()

work1 = worker1()
work2 = worker2()

work1.moveToThread(thr1)
work2.moveToThread(thr2)

# I have a signal coming in from main thread
app.connect(myapp, QtCore.SIGNAL('start1'), work1.run1())
app.connect(myapp, QtCore.SIGNAL('start1'), work2.run2())

thr1.start()
thr2.start()

Is this kind of QThread coding incorrect if I want to setup two Qthreads? 如果要设置两个Qthread,这种QThread编码是否正确?

I am getting a "Segmentation fault" when I try to start the program, but as soon as I take the second app.connect away, it runs fine. 尝试启动程序时出现“分段错误”,但是一旦我离开第二个app.connect,它就会运行正常。

I was wondering if anyone can tell me where I've gone wrong. 我想知道是否有人可以告诉我我哪里出错了。

Thanks! 谢谢!

When you connect your signals with: 当您通过以下方式连接信号时:

app.connect(myapp, QtCore.SIGNAL('start1'), work1.run1())

You are actually executing the run function, not just connecting it. 您实际上是在执行run函数,而不仅仅是连接它。 You want to leave out the "()" or else python executes the function and tries to connect whatever it returns. 您要忽略“()”,否则python将执行该函数并尝试连接返回的任何内容。

EDIT: 编辑:

Two more suggestions in response to your comment saying you took out the "()". 针对您的评论说您取出了“()”,还有另外两个建议。 First, I've never seen someone rename the run function when using the QtThread class and you may want to try the same code where both run1 and run2 are actually just named "run". 首先,我从未见过有人在使用QtThread类时重命名run函数,并且您可能想尝试使用相同的代码,其中run1和run2实际上都被命名为“ run”。 Check out this thread for some good example: How to use QThread correctly in pyqt with moveToThread()? 看看这个线程的一些好例子: 如何通过moveToThread()在pyqt中正确使用QThread?

Second, can you post the actual error? 其次,您可以发布实际错误吗? Does it like anything like the one in this thread: Is this PyQt 4 python bug or wrongly behaving code? 它是否类似于该线程中的任何东西: 是PyQt 4 python错误还是行为错误的代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM