Python线程处理join()多线程

2024-04-25 18:07:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,其中执行简单任务的线程每3分钟启动一次。我正在使用线程调度模块

由于多线程的性质,线程使用相同的资源

What i need to achieve ?

创建新线程时,我想检查是否有任何runningthread;如果有,则等待运行线程终止,然后启动新线程

What i have tried ?

 import threading

def run_threaded(job_fn):
    job_thread = threading.Thread(target=job_fn)
    bot.logger.info(" --------------No of active threads : "+threading.activeCount())
    job_thread.start()
    job_thread.join()
    bot.logger.info(" --------------No of active threads : " + threading.activeCount())


schedule.every(3).minutes.do(run_threaded, job)


while True:
    schedule.run_pending()

Note: On the example above every job_thread needs 5 minutes to complete . Thus it creates 1 thread every 6 minutes .

据我所知,job\u thread.join()行正在连接主线程(与任何其他活动线程)。尽管调度被阻塞,因此在前一个线程完成之前,不能实例化任何其他线程。对吗?如果是的话,这是一个很好的做法吗

为了记录在案。。脚本在运行线程时是否可以执行其他代码块?或者它可以在前一个线程完成之前实例化其他线程,如果它们要执行另一个作业,比如说job2


Tags: torun脚本botjoblogger调度线程
1条回答
网友
1楼 · 发布于 2024-04-25 18:07:58

下面是一个简单的示例,展示了几个正在启动的线程,每个线程都将在不同的时间终止自己,以及主线程如何确定每个线程何时终止

#!/usr/bin/env python3
import threading
import time
import queue

class Worker(threading.Thread):
    def __init__(self, duration, tqueue):
        self.duration = duration
        self.tqueue = tqueue
        super().__init__()
    def run(self):
        # Do real work here instead of just sleeping
        time.sleep(self.duration)
        # Tell parent we are gone by putting our instance to the queue
        self.tqueue.put(self)

def main():
    thr_duration = [2.0, 1.5, 0.5, 2.7, 1.25]
    workers = []
    thr_queue = queue.Queue()

    # Start all threads
    for dur in thr_duration:
        worker = Worker(dur, thr_queue)
        worker.start()
        workers.append(worker)
        print("Started thread {}, duration {}".format(worker.name, dur))

    # Wait for all threads to terminate
    while workers:
        worker = thr_queue.get()
        worker.join()
        print("Reaped thread {}".format(worker.name))
        workers.remove(worker)

if __name__ == '__main__':
    main()

相关问题 更多 >