一、多线程简单示例
import threading,time
print('第一线程(默认):程序开始啦!')
def takeANap():
time.sleep(5)
print('第二线程:5秒到,我醒来啦!')
#创建并启动多线程
t=threading.Thread(target=takeANap)
t.start()
print('第一线程(默认):程序结束啦!')
'''
输出:
第一线程(默认):程序开始啦!
第一线程(默认):程序结束啦!
>>> 第二线程:5秒到,我醒来啦!
'''
二、多线程传递多参数、可选参数示例
import threading
##多线程传递多参数print('Cats','Dogs','Frogs',sep='&')=>Cats & Dogs & Frogs:
threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],kwargs={'sep': ' & '})
threadObj.start()
##输出:Cats & Dogs & Frogs
三、并发问题
可以轻松地创建多个新线程,让它们同时运行。但多线程也可能会导致所谓的并发问题。如果这些线程同时读写变量,导致互相干扰,就会发生并发问题。并发问题可能很难一致地重现,所以难以调试。多线程编程本身就是一个广泛的主题。必须记住的是:为了避免并发问题,绝不让多个线程读取或写入相同的变量。当创建一个新的Thread 对象时,要确保其目标函数只使用该函数中的局部变量。这将避免程序中难以调试的并发问题。
多线程实战,多线程下载漫画:
#! python3
# multidownloadXkcd.py - Downloads XKCD comics using multiple threads.
import requests, os, bs4, threading
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
def downloadXkcd(startComic, endComic):
for urlNumber in range(startComic, endComic):
# Download the page.
print('Downloading page http://xkcd.com/%s...' % (urlNumber))
res = requests.get('http://xkcd.com/%s' % (urlNumber))
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
# Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
# Save the image to ./xkcd
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
# Create and start the Thread objects.
downloadThreads = [] # a list of all the Thread objects
for i in range(0, 1400, 100): # loops 14 times, creates 14 threads
downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99))
downloadThreads.append(downloadThread)
downloadThread.start()
# Wait for all threads to end.
for downloadThread in downloadThreads:
downloadThread.join()
print('Done.')
seo优化_前端开发_渗透技术








