我对 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)
===================================================================
注意事项:
-- 这个工具有一个图形用户界面,如果我在主循环中运行 time.sleep(),它往往会锁定和卡住,这就是为什么我认为多线程是一个很好的解决方案(随时纠正我如果那是错误的)。或者可能是一种不同的等待方式,它不会在等待时卡住整个线程。
-- 程序在 while 循环中卡住,是否有一种无需循环即可执行此检查的方法,可能类似于回调(如在 do_stuff() 函数结束时模拟按下按钮)?
-- 我也想尝试为此添加一些错误检查,因此根据 do_stuff() 的结果返回不同的错误代码(请牢记)。
如果信息不够,我深表歉意;如果需要,请随时询问更多具体信息。真的,伙计们,我很感激我能得到的所有帮助,我只是想对这些东西有一个深入的了解!谢谢!
最佳答案
线程有一些开销,它们都共享相同的 CPU 核心,线程非常适合等待用户输入或下载文件以及其他 i/o 受限的事情,如果您需要更多的计算能力,我建议您使用多处理模块(参见 Multiprocessing vs Threading Python)
线程的另一个问题是它们由于全局解释器锁而“锁定”,这是因为在任何时候只允许 1 个线程写入内存,荒谬的结果是许多线程会导致你的程序崩溃因为他们都在等待访问内存
关于python - 多线程工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17294642/