简体   繁体   English

在Python中管理线程执行

[英]Managing thread execution in Python

I am currently using worker threads in Python to get tasks from a Queue and execute them, as follows: 我目前在Python中使用辅助线程从队列中获取任务并执行任务,如下所示:

from queue import Queue
from threading import Thread

def run_job(item)
    #runs an independent job...
    pass    

def workingThread():
    while True:
        item = q.get()
        run_job(item)
        q.task_done()

q = Queue()
num_worker_threads = 2

for i in range(num_worker_threads):
    t = Thread(target=workingThread)
    t.daemon = True
    t.start()

for item in listOfJobs:
    q.put(item)

q.join()

This is functional, but there is an issue: some of the jobs to be executed under the run_job function are very memory-demanding and can only be run individually. 这是功能性的,但是存在一个问题:在run_job函数下要执行的某些作业对内存的要求很高,并且只能单独运行。 Given that I could identify these during runtime, how could I manage to put the parallel worker threads to halt their execution until said job is taken care of? 鉴于我可以在运行时识别出这些错误,我如何设法让并行工作线程停止执行,直到完成上述工作为止?

Edit: It has been flagged as a possible duplicate of Python - Thread that I can pause and resume , and I have referred to this question before asking, and it surely is a reference that has to be cited. 编辑:它已被标记为可能重复的Python-Thread,我可以暂停和继续 ,并且在问之前我已经提到了这个问题,并且它肯定是必须被引用的参考。 However, I don't think it adresses this situation specifically, as it does not consider the jobs being inside a Queue, nor how to specifically point to the other objects that have to be halted. 但是,我认为它不专门解决这种情况,因为它既不考虑队列中的作业,也不考虑如何专门指向其他必须暂停的对象。

I would pause/resume the threads so that they run individually. 我会暂停/恢复线程,以便它们分别运行。 The following thread Python - Thread that I can pause and resume indicates how to do that. 以下线程Python-我可以暂停和恢复的线程指示如何执行此操作。

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

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