1. 程式人生 > 其它 >python使用_thread模組進行多執行緒任務排程。

python使用_thread模組進行多執行緒任務排程。

技術標籤:pythonpython多執行緒

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

最後實現了任務的多執行緒同時進行,結果如下:
在這裡插入圖片描述