python - 多线程 python 应用程序在运行其线程时挂起

标签 python multithreading loops sleep blocking

我正在尝试创建一个可用作 DBus 服务的 MainObject。这个 MainObject 应该始终保持对其他对象/进程的响应,并且即使在处理它的项目时也是如此。因此,项目在单独的线程中一个接一个地处理(队列式)。您可以通过 DBus 或命令行向 MainObject 添加项目。我简化了示例(没有 dbus,没有命令行)来显示我的问题。

我的问题是,如果我重新启用“tt.join()”,应用程序会按预期工作,但会阻塞其他进程。难怪 tt.join 使应用程序等待,直到单独的线程完成其工作。另一方面,如果“tt.join()”保持禁用状态,应用程序不会阻止外部 dbus 事件,但永远不会出现“ThreadTest done!” (看实际输出)

我想要的是我的预期输出,但应用程序应保持响应。

#!/usr/bin/python2.5

import gobject
import threading
import re
import time

class ThreadTest(threading.Thread):

  def __init__(self):
    threading.Thread.__init__ (self)    
    print '  ThreadTest created!'

  def run(self):
    print '  ThreadTest running ...'
    time.sleep(1)
    print '  ThreadTest done!'
    return True

class MainObject():
  def __init__(self):
    self.timer = gobject.timeout_add(1000, self.update)
    self.loop  = gobject.MainLoop()
    print 'MainObject created!'

  def update(self):
    print 'MainObject updating ...'
    if self.check_running() == False:
      tt = ThreadTest()
      tt.start()
      #tt.join()
    return True

  def check_running(self):
    running = False
    expr = re.compile('ThreadTest')
    for threadstr in threading.enumerate():
      matches = expr.findall(str(threadstr))
      if matches:
        running = True
    return running  


mo = MainObject()
mo.loop.run()

预期输出:

MainObject created!
MainObject updating ...
  ThreadTest created!
  ThreadTest running ...
  ThreadTest done!
MainObject updating ...
  ThreadTest created!
  ThreadTest running ...
  ThreadTest done!
MainObject updating ...
  ThreadTest created!
  ThreadTest running ...
  ThreadTest done!
MainObject updating ...
  ThreadTest created!
  ThreadTest running ...
  ThreadTest done!
MainObject updating ...
  ThreadTest created!
  ThreadTest running ...
  ThreadTest done!

实际输出:

MainObject created!
MainObject updating ...
  ThreadTest created!
  ThreadTest running ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...

最佳答案

默认情况下,gobject 绑定(bind)不是多线程感知的。请在导入 gobject 后尝试执行以下操作:

gobject.threads_init()

关于python - 多线程 python 应用程序在运行其线程时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2006132/

相关文章:

python - HackerRank 阶梯 Python

wpf - 在 STA 线程 WPF 下运行多个 xunit 测试时出现问题

c++ - 如果达到结束条件,是否可以在 C++ 中退出 for before time?

c# - 为什么是 i++ "unreachable code"?

php - 迭代查询并将数字分组

python - 获取 BeautifulSoup 中表的内容

python - PyDev + Django - 来自导入的 undefined variable

python - 如何在 Python 中获取 SQLite 结果/错误代码

multithreading - sync.WaitGroup 是 "synchronization primitive"吗?

android - 创建一个在 UI 线程 Android 中更新的秒表