多线程和子进程未在 python 中生成正确数量的线程



我正在创建一个小的python脚本来创建n个线程,每个线程在我的Web应用程序上调用curl m次。

脚本

被调用./multithreadedCurl.py 10 100

我希望 curl 执行 b 10*100 = 1000 次。但是我看到它正在创建 n 个线程,但每个线程只调用一次 curl。
这是因为我正在使用子流程吗?

Python 版本 Python 2.7.2操作系统: Mac OSX 10.8.2 (Mountain Lion)

非常感谢任何帮助,我对python非常陌生,这是我python开发的第二天。

#!/usr/bin/python

import threading
import time
import subprocess
import sys
import math
# Define a function for the thread
def run_command():
        count  = 0
        while (count < int(sys.argv[2])):
                subprocess.call(["curl", "http://127.0.0.1:8080"])
                count += 1
threadCount = 0
print sys.argv[0]
threadLimit = int(sys.argv[1])
while threadCount < threadLimit:
        t=threading.Thread(target=run_command)
        t.daemon = True  # set thread to daemon ('ok' won't be printed in this case)
        t.start()
        threadCount += 1`

通过设置t.daemon = True你说

http://docs.python.org/2/library/threading.html线程可以标记为"守护程序线程"。此标志的意义在于,当只剩下守护进程线程时,整个 Python 程序将退出。初始值继承自创建线程。可以通过守护程序属性设置该标志。

因此,您应该使用t.daemon = False或等待所有线程完成join

threads = []
while len(threads) < threadLimit:
    t=threading.Thread(target=run_command)
    threads.append(t)
    t.daemon = True
    t.start()
[thread.join() for thread in threads]

最新更新