python使用_thread模块进行多线程任务调度。
因为最近有个项目要求两个任务随机时间间隔执行,最开始想到的时使用time模块的sleep函数进行时间间隔,但考虑到sleep是一个阻塞函数,也就是说sleep着段时间,什么都不能做。那么想要两个任务随机时间,且相互没有影响,所以开始想到使用多线程进行任务调度。
python的多线程实现方法有很多,这里使用最简单的_thread模块。该模块本身是python中的,在python3中因为有了threading模块,所以该模块在python3中已经被弃用,但考虑到兼容性,所以python3将其改名为——“_thread”。
使用该模块,核心是
_thread.start_new_thread ( function, args[, kwargs] )~~
这一句,其中
function - 线程函数。
args - 传递给线程函数的参数,他必须是个tuple类型。
kwargs - 可选参数。
使用该语句启动的每一个函数单独占用一个线程。从而实现了多线程并行执行。
本次我的任务是对几个目标进行攻击,产生一些可用数据供展示使用,下面是我的代码
import requests
import time
import _thread
import random
def attacktech(t_min, t_max, per, url):
while True:
i = random.randint(1, 100)
t1 = random.randint(t_min, t_max)
if i <= per:
re = requests.get(url=url)
print(re.url, t1)
time.sleep(t1)
def upfiletest(tmin, tmax, per):
upFile = {"userUpFile": open("C:\\Users\\Tercel\\Desktop\\h14k.asp", "rb")}
postData = {"userSubmit": "submit"}
while True:
i = random.randint(1, 100)
t2 = random.randint(tmin, tmax)
if i <= per:
upfile = requests.post(url="http://localhost:8080/upfile.php",
files=upFile, data=postData)
print(upfile.url, t2)
time.sleep(t2)
try:
_thread.start_new_thread(attacktech, (1, 3, 70, "http://localhost:8080/test.ini"))
_thread.start_new_thread(attacktech, (4, 6, 70, "http://localhost:8080/test.asp.png"))
_thread.start_new_thread(upfiletest, (1, 5, 70))
_thread.start_new_thread(attacktech, (1, 5, 50, "http://localhost:8081/test.ini"))
_thread.start_new_thread(attacktech, (1, 5, 50, "http://localhost:8082/test.ini"))
except:
print ("Error: 无法启动线程")
while 1:
pass
最后实现了任务的多线程同时进行,结果如下: