【问题标题】:Multiple Threads in Python with wrapped C functionsPython中的多线程与包装的C函数
【发布时间】:2014-06-24 00:24:42
【问题描述】:

我有一个 python 代码,它使用 wx 创建一个 GUI,允许用户在他们的计算机上选择一个文件,然后调用一个我用 swig 包装的 C 函数,它使用这个文件并进行计算并将其保存到一个新文件.我希望这个函数调用在一个线程中运行,而 wx 窗口不会停止响应,而且我还有一个加载栏,它估计完成计算所需的时间并每秒更新进度。目前,代码开始在线程中运行加载条函数,然后开始在线程中运行计算,但这会导致加载条函数暂停。几分钟后完成所有计算后,加载栏功能恢复。我希望这些线程并行运行,但我无法让它与这个包装函数一起工作(其他时候我使用这个线程它已经工作了)。

我的部分代码如下:

thread.start_new_thread(self.loading_bar, (max_count,))
thread.start_new_thread(self.run_interpolation, (option,))

def loading_bar(self, max_count):
    loaded = 1.0
    print 180 + (max_count / 2), loaded
    while loaded < 100.0:
        print 180 + (max_count / 2), loaded
        sleep(1)
        wx.CallAfter(self.gauge.SetValue, loaded)
        loaded += 100.0 / (180 + (max_count / 2))
    sleep(2)
    wx.CallAfter(self.gauge.SetValue, 0)

def run_interpolation(self, option):
    weather_interp.main_func(self.input[1], self.input[2], self.location, option)

我听说多处理模块和线程模块比线程模块好,但我不明白为什么,尝试使用它们似乎也不起作用。

【问题讨论】:

    标签: python multithreading python-2.7


    【解决方案1】:

    您可能希望使用threading 库而不是低级thread 库。由于您当前的任务不受处理器限制,因此您实际上不需要利用多个处理器或多个内核,因此我不会担心多处理——您需要多个 Python 线程,但您不需要多个操作系统线程。

    使用线程库的简单示例:

    #!/usr/bin/env python
    import threading
    import time
    
    def foo():
      print 'foo 1'
      time.sleep(0.2)
      print 'foo 2'
    
    def bar():
      time.sleep(0.1)
      print 'bar 1'
      time.sleep(0.2)
      print 'bar 2'
    
    threading.Thread(target=foo).start()
    threading.Thread(target=bar).start()
    

    这应该打印出来

    foo 1
    bar 1
    foo 2
    bar 2
    

    所以你知道它是交错的并且线程正在工作。根据您的代码 sn-p,看起来您的线程内容很好。

    因此,我怀疑问题出在 CallAfter 调用上。根据its documentation,CallAfter 在当前事件处理程序退出后运行。根据您的 sn-p,您似乎没有退出事件处理程序。也许您想直接在循环中设置仪表的值?

    【讨论】:

      【解决方案2】:

      问题是我调用的 c 包装函数。为了解决这个问题,我在编译接口文件时添加了一个 -threads 标志。

      【讨论】:

        猜你喜欢
        • 2016-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-23
        • 2012-09-17
        • 1970-01-01
        • 2018-10-12
        • 2020-06-15
        相关资源
        最近更新 更多