简体   繁体   English

在Pygtk中使用线程

[英]Use Thread in Pygtk

I'm in a project to develop a chat application like netmeeting. 我正在开发一个类似于netmeeting的聊天应用程序的项目。 I want to separate thread one is for GUI (gtk.main) another is simultaneously accepting client chat request (socket.accept) . 我想分开一个线程用于GUI(gtk.main),另一个线程同时接受客户端聊天请求(socket.accept)。 But there is a problem.. 但有个问题..

here is my simple line of code which is 2nd thread for accepting client request: 这是我的简单代码行,它是用于接受客户端请求的第二个线程:

while True:
    self.new_sock,self.client_addr = self.sock.accept()
    #CloseDialog is a messege box
    respons=self.CloseDialog.run()
    if respons==gtk.RESPONSE_YES:
        #Call a Chat Window         
    elif respons==gtk.RESPONSE_NO:
        #Close the requested socket

when i run the application it switch to the gtk.main loop and my 2nd thread is unable to run. 当我运行应用程序时,它切换到gtk.main循环,而我的第二个线程无法运行。 is there any process to run those thread parallel, But I'm very confuse to implement this. 是否有任何进程可以并行运行那些线程,但是我对此感到非常困惑。 if you need any further information I will give it to you. 如果您需要任何进一步的信息,我会给您。 Please help me.. thanks in advance 请帮助我..在此先感谢

Have a look at PyGTK FAQ . 看看PyGTK常见问题解答 In particular, I suggest the gobject.idle_add() approach. 特别是,我建议使用gobject.idle_add()方法。 When your second thread needs any GUI interaction, schedule some code running in the main thread with `gobject.idle_add(), sort of like this: 当您的第二个线程需要任何GUI交互时,可以使用gobject.idle_add()安排一些在主线程中运行的代码,如下所示:

def ask_close ():
    self.CloseDialog.run ()
gobject.idle_add (ask_close)

Then you'd need to wait for some mutex X for when answer (in the main thread) arrives. 然后,您需要等待一些互斥锁X以便答案(在主线程中)到达时。 I also recommend not using modal dialogs ( run() ), because that largely defeats the purpose of having multiple threads. 我还建议不要使用模式对话框( run() ),因为这在很大程度上违反了具有多个线程的目的。 Instead, use present() and connect a callback to response signal. 而是使用present()并将回调连接到response信号。 This callback would release mutex X so that the second thread can stop waiting and process the answer. 此回调将释放互斥锁X以便第二个线程可以停止等待并处理答案。

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

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