3

我对 python 脚本仍然很陌生,并且正在尝试通过添加多线程支持来加速和平滑我的一些工具。我觉得我可能对这里的一些工作流理论有误解,所以如果我应该以另一种方式做这件事,请随意改变我的心态。基本上我想做的是以下几点:

==================================================================
###Pseudo-code -- I apologize if this does not follow existing conventions
main_function()
    if do_stuff_function is not running:
        Thread1 = new thread running do_stuff_function

do_stuff_function(args)
    do some stuff
    wait for 60 seconds (possibly using time.sleep())
    end thread (tell main_function that the thread is done)
==================================================================
###Abridged code
def main(self):
      check = True
      index = 0
      While index < 5:
          if check == True:
              check = False
              thread1 = threading.Thread(target=self.doStuff, args=(self, index))



def do_stuff(self, index):
     ###Stuff happens here####

     ###iterate index and somehow return it (possibly a global variable)
     time.sleep(60)
     ###somehow end the thread (still not entirely sure how to do that)

===================================================================

笔记:

-- 这个工具有一个 gui,如果我在主循环中运行 time.sleep(),它往往会锁定和冻结,这就是为什么我认为多线程是一个很好的解决方案(如果是,请随时纠正我错误的)。或者可能是另一种等待方式,在等待时不会冻结整个线程。

-- 程序在 while 循环中冻结,有没有办法在不需要循环的情况下进行检查,可能类似于回调(比如 do_stuff() 函数结束时的模拟按钮按下)?

-- 我也希望尝试为此添加一些错误检查,因此根据 do_stuff() 的结果返回不同的错误代码(请记住)。

如果信息不足,我深表歉意;如果您需要,请随时询问更具体的信息。真的,伙计们,我感谢我能得到的所有帮助,我只是想深入了解这些东西!谢谢!

4

1 回答 1

2

线程有一些开销,它们都共享相同的 CPU 内核,线程非常适合等待用户输入或下载文件以及其他 I/O 受限的事情,如果您需要更多计算能力,我建议您使用多处理模块(请参阅多处理与线程 Python

线程的另一个问题是它们因为全局解释器锁而“锁定”,这是因为在任何时候只允许 1 个线程写入内存,荒谬的结果是,对于许多线程来说,因为它们是都在等待访问内存

于 2013-06-25T15:10:26.190 回答