2012-11-11 22 views
0

我正在創建一個小python腳本來創建n個線程,並且每個線程在我的web應用程序上調用curl m次。多線程和子進程不會在python中產生正確數量的線程

腳本調用 ./multithreadedCurl.py 10 100

我期望捲曲到B所執行10×100 = 1000次。 但是我看到它創建了n個線程,但每個線程只調用一次curl。
這是由於我使用子進程的事實嗎?

Python版本的Python 2.7.2 操作系統:Mac OSX 10.8.2(山獅)

任何幫助非常感謝,我很新的蟒蛇,這是我的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` 

回答

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] 
+0

這解決了我的問題。感謝您的解決方案 –

+0

一個側面說明:更好的循環:對於我在範圍內(threadLimit): – Bob

相關問題