我有一个包含日期列表的文本文件。我想将每个日期作为参数传递给shell脚本,并在文件中为所有指定的日期运行脚本。在
我想用python并行执行这个任务。由于脚本有复杂的逻辑,为了监视执行情况,我希望一次运行5个实例。脚本一完成python就必须启动新线程。在
import threading
import time
class mythread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.h = i
# Script will call the function
def run(self):
time.sleep(1)
print("Value send ", self.h)
f = open('C:\Senthil\SenStudy\Python\Date.txt').readlines()
num = threading.activeCount()
for i in f:
print("Active threads are ", num)
time.sleep(1)
if threading.activeCount() <= 5:
thread1 = mythread(i)
thread1.start()
else:
print("Number of Threads are More than 5 .. going to sleep state for 1 mint ...")
time.sleep(1)
我尝试使用threading.activeCount()
来获得运行的线程数,但从一开始它就说线程数是30(这是文件中所有日期项的数目)。在
您的问题似乎是为python进程池或线程池量身定做的。如果每个“线程”的输入参数只是一个日期,我认为进程池可能更好,因为线程之间的同步可能很棘手。在
请阅读
multiprocessing
模块的documentation,看看它是否解决了您的问题。如果你对此有任何疑问,我很乐意澄清。在(流程池的示例就在文档的开头。如果您真的认为您需要一个线程池,语法应该是相同的-只需将} )
multiprocessing
替换为^{在确定需要线程而不是进程的情况下,可以使用
ThreadPoolExecutor
来运行固定数量的工作线程来执行此作业:如果使用Python 2,则必须先安装
^{pr2}$futures
库才能正常工作:相关问题 更多 >
编程相关推荐