如何在我的命令上停止python线程?

时间:2018-03-13 11:12:46

标签: python multithreading api python-requests stress-testing

我正在尝试制作一个脚本来测试我的api。它应该创建X线程,并且每个线程都应该向我的服务器发送请求并记录数据,直到我将其停止( ctrl + c 或某些命令)

我该如何实施停止? 谢谢!

我的代码:

import requests, os, time, sys
from threading import Thread

myThreads = 5

log = ["errorCode, before, after"]
def addToLog(errorCode, before, after):
    log.append(str(errorCode)+","+str(before)+","+str(after))

def saveLogToFile():
    logFile = open('log.csv', 'w')
    for line in log:
        logFile.write(line+"\n")

def sendRequest():
    before = time.time()
    response = requests.post("https://localhost/api", data= {
        "action": 0,
        "id": 1,
        })
    after = time.time()
    json = response.json()
    return json["errorCode"], before, after

def work():
    while True:
        errorCode, before, after = sendRequest()
        addToLog(errorCode, before, after)

for i in range(myThreads):
    t = Thread(target=work)
    t.daemon = True
    t.start()

saveLogToFile()

1 个答案:

答案 0 :(得分:0)

为了让你的程序运行足够长的时间让所有工人完成所有工作,“加入”工作线程。 “加入”一个线程是等待线程完成运行的行话。在程序中加入线程有两个简单的选项。首先,艰难的方式:

worker_threads = []
for i in range(myThreads):
    t = Thread(target=work)
    t.daemon = True
    t.start()
    worker_threads.append(t)

saveLogToFile()
for t in worker_threads:
    t.join()

接下来,简单的方法。主线程退出后,非守护程序线程自动连接。所以只需停止制作你的线程守护进程:

for i in range(myThreads):
    t = Thread(target=work)
    t.start()

saveLogToFile()