1
我有一个由ID组成的list
,每天约50k。为什么我的线程停止?
,我必须每天进行50k的请求到服务器{服务器是在同一个城市},并获取信息,并将其存储到数据库中。我已经做了,使用loop
和Threads
和我“已经注意到时间未知时间后它停止的读取和存储...
看看我的代码片段
import re,urllib,urllib2
import mysql.connector as sql
import threading
from time import sleep
import idvalid
conn = sql.connect(user="example",password="example",host="127.0.0.1",database="students",collation="cp1256_general_ci")
cmds = conn.cursor()
ids=[] #here is going to be stored the ID's
def fetch():
while len(ids)>0:#it will loop until the list of ID's is finish
try:
idnumber = ids.pop()
content = urllib2.urlopen("http://www.example.com/fetch.php?id="+idnumber,timeout=120).read()
if content.find('<font color="red">') != -1:
pass
else:
name=content[-20:]
cmds.execute("INSERT INTO `students`.`basic` (`id` ,`name`)VALUES ('%s', '%s');"%(idnumber,name))
except Exception,r:
print r,"==>",idnumber
sleep(0.5)#i think sleep will help in threading ? i'm not sure
pass
print len(ids)#print how many ID's left
for i in range(0,50):#i've set 50 threads
threading.Thread(target=fetch).start()
output
的:它会继续打印多少号的左,在未知的时刻它停止打印并提取&存储
'mysql.connector'定义''1''threadsafety'](http://www.python.org/dev/peps/pep-0249/#threadsafety),这意味着你不应该在没有同步的情况下在线程之间共享连接和游标。 – mata
所以,我可以修改它吗? – Hamoudaq
只是在'fetch'函数内移动'sql.connect'和'conn.cursor()' – mpaolini