1、Python单线程
python的线程需要导入threading包,一般默认都有的,具体创建单线程并测试代码如下
import threading
import time
def test(hostpool):
for i in range(5):
print("test:",i," ",hostpool)
time.sleep(1)
thread=threading.Thread(target=test,kwargs={"hostpool":"def"})
# target是线程调用的函数,kwargs是传给target函数的参数名称字典
thread.start()
# 开启线程
2、Python多线程
由于测试的需要,需要在多线程内加入定时任务,这里采用的是schedule模块来辅助实现相关功能
测试代码如下:
import schedule
import time
import datetime
import threading
def test(hostpool):
# 实际被调用的函数
print("------",hostpool,":",datetime.datetime.now())
def test_predict(hostpool):
# 定时任务
schedule.every(10).seconds.do(test,{"hostpool":hostpool})
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == '__main__':
f=open("hostpool.txt")
data=f.readlines()
hostpools=[]
for d in data:
hostpool=d.split("-")[0]
hostpools.append(hostpool)
# 创建线程池并启动
threadpool=[]
for hostpool in hostpools:
th=threading.Thread(target=test_predict,kwargs={"hostpool":hostpool})
threadpool.append(th)
for th in threadpool:
th.start()
for th in threadpool:
threading.Thread.join(th)
展示结果: