import time
import urllib2
defget_responses():
urls=[
‘http://www.baidu.com',
‘http://www.amazon.com',
‘http://www.ebay.com',
‘http://www.alibaba.com',
‘http://www.1sucai.cn'
]
start=time.time()
forurlinurls:
printurl
resp=urllib2.urlopen(url)
printresp.getcode()
print”Elapsed time: %s”%(time.time()-start)
get_responses()
import urllib2
import time
from threading import Thread
classGetUrlThread(Thread):
def__init__(self, url):
self.url=url
super(GetUrlThread,self).__init__()
defrun(self):
resp=urllib2.urlopen(self.url)
printself.url, resp.getcode()
defget_responses():
urls=[
‘http://www.baidu.com',
‘http://www.amazon.com',
‘http://www.ebay.com',
‘http://www.alibaba.com',
‘http://www.1sucai.cn'
]
start=time.time()
threads=[]
forurlinurls:
t=GetUrlThread(url)
threads.append(t)
t.start()
fortinthreads:
t.join()
print”Elapsed time: %s”%(time.time()-start)
get_responses()
from threading import Thread
#define a global variable
some_var=0
classIncrementThread(Thread):
defrun(self):
#we want to read a global variable
#and then increment it
globalsome_var
read_value=some_var
print”some_var in %s is %d”%(self.name, read_value)
some_var=read_value+1
print”some_var in %s after increment is %d”%(self.name, some_var)
defuse_increment_thread():
threads=[]
foriinrange(50):
t=IncrementThread()
threads.append(t)
t.start()
fortinthreads:
t.join()
print”After 50 modifications, some_var should have become 50″
print”After 50 modifications, some_var is %d”%(some_var,)
use_increment_thread()
from threading import Lock, Thread
lock=Lock()
some_var=0
classIncrementThread(Thread):
defrun(self):
#we want to read a global variable
#and then increment it
globalsome_var
lock.acquire()
read_value=some_var
print”some_var in %s is %d”%(self.name, read_value)
some_var=read_value+1
print”some_var in %s after increment is %d”%(self.name, some_var)
lock.release()
defuse_increment_thread():
threads=[]
foriinrange(50):
t=IncrementThread()
threads.append(t)
t.start()
fortinthreads:
t.join()
print”After 50 modifications, some_var should have become 50″
print”After 50 modifications, some_var is %d”%(some_var,)
use_increment_thread()
from threading import Thread
import time
classCreateListThread(Thread):
defrun(self):
self.entries=[]
foriinrange(10):
time.sleep(1)
self.entries.append(i)
printself.entries
defuse_create_list_thread():
foriinrange(3):
t=CreateListThread()
t.start()
use_create_list_thread()
from threading import Thread, Lock
import time
lock=Lock()
classCreateListThread(Thread):
defrun(self):
self.entries=[]
foriinrange(10):
time.sleep(1)
self.entries.append(i)
lock.acquire()
printself.entries
lock.release()
defuse_create_list_thread():
foriinrange(3):
t=CreateListThread()
t.start()
use_create_list_thread()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有