2011-07-18 35 views
-1

我試圖運行此代碼:Python的主題:無法啓動新的線程

def VideoHandler(id): 
    try: 
     cursor = conn.cursor() 
     print "Doing {0}".format(id) 
     data = urllib2.urlopen("http://myblogfms2.fxp.co.il/video" + str(id) + "/").read() 
     title = re.search("<span class=\"style5\"><strong>([\\s\\S]+?)</strong></span>", data).group(1) 
     picture = re.search("#4F9EFF;\"><img src=\"(.+?)\" width=\"120\" height=\"90\"", data).group(1) 
     link = re.search("flashvars=\"([\\s\\S]+?)\" width=\"612\"", data).group(1) 
     id = id 
     print "Done with {0}".format(id) 
     cursor.execute("insert into videos (`title`, `picture`, `link`, `vid_id`) values('{0}', '{1}', '{2}', {3})".format(title, picture, link, id)) 
     print "Added {0} to the database".format(id) 
    except: 
     pass 

x = 1 
while True: 
    if x != 945719: 
     currentX = x 
     thread.start_new_thread(VideoHandler, (currentX)) 
    else: 
     break 
    x += 1 

,它說「無法啓動新的線程」

+5

我不是線程專家,但我相當確信您的計算機將具有有限的尋址空間,即不太可能您可以創建945718個併發線程。此外,您可以嘗試更好地格式化您的代碼,因爲它不會以所示的格式運行。 – Raceyman

+0

我們能否看到回溯(不僅是「無法啓動新的線程」,這太過於通用)?建議:在你的try塊內部的操作之前,我建議使用lock.acquire()和lock.release(),因爲你正在對數據庫執行操作(所以這是一個關鍵部分) –

+0

做了答案我提議解決你的問題?如果是這樣,請接受它。 –

回答

7

該錯誤的真正原因是最有可能的是你創建太多線程(超過100k !!!)並達到操作系統級限制。

您的代碼可以在很多方面,除了這個被改進:

  • 不要使用低級別thread模塊,使用Threadthreading模塊中。
  • 加入代碼末尾的線程
  • 將您創建的線程數量限制爲合理:處理所有元素,創建少量線程並讓每個線程處理整個數據的一個子集(this是我的建議之下,但你也可以採取與工作線程從queue.Queue實例讓他們的數據)
  • 從未生產者 - 消費者模式,曾經在你的代碼中except: pass聲明。如果你這樣做,或者 ,如果你的代碼不起作用,不要在這裏哭泣,而你 找不到原因。 :-)

這裏有一個建議:

from threading import Thread 
import urllib2 
import re 

def VideoHandler(id_list): 
    for id in id_list: 
     try: 
      cursor = conn.cursor() 
      print "Doing {0}".format(id) 
      data = urllib2.urlopen("http://myblogfms2.fxp.co.il/video" + str(id) + "/").read() 
      title = re.search("<span class=\"style5\"><strong>([\\s\\S]+?)</strong></span>", data).group(1) 
      picture = re.search("#4F9EFF;\"><img src=\"(.+?)\" width=\"120\" height=\"90\"", data).group(1) 
      link = re.search("flashvars=\"([\\s\\S]+?)\" width=\"612\"", data).group(1) 
      id = id 
      print "Done with {0}".format(id) 
      cursor.execute("insert into videos (`title`, `picture`, `link`, `vid_id`) values('{0}', '{1}', '{2}', {3})".format(title, picture, link, id)) 
      print "Added {0} to the database".format(id) 
     except: 
      import traceback 
      traceback.print_exc() 

conn = get_some_dbapi_connection()   
threads = [] 
nb_threads = 8 
max_id = 945718 
for i in range(nb_threads): 
    id_range = range(i*max_id//nb_threads, (i+1)*max_id//nb_threads + 1) 
    thread = Thread(target=VideoHandler, args=(id_range,)) 
    threads.append(thread) 
    thread.start() 

for thread in threads: 
    thread.join() # wait for completion 
+0

它說「未定義變量線程」 – user850019

+0

它不應該。我不明白:-)我只在線程內的conn對象上發生錯誤。 –

+2

+1對於從未使用過的評論除外:通過 – Foon

0

OS擁有的線程數量的限制。所以你不能創建太多的線程超過限制。 ThreadPool應該是你做這個高併發性工作的不錯選擇。