Python–多线程基础
1.利用多线程和多进程实现基础的同时下载文件
from random import randint
from time import time,sleep
from multiprocessing import Process #多进程
from os import getpid
from threading import Thread #多线程
def download_task(filename):
print('启动下载进程,进程号【%d】' % getpid())
print("开始下载%s。。。。。"%filename)
tim_to_downaload = randint(5,10)
sleep(tim_to_downaload)
print("%s下载完成,总共耗费%s秒" % (filename,tim_to_downaload))
def main():
start=time()
p1 = Process(target=download_task,args=('Python从入门到入院',)) #多进程
p1 = Thread(target=download_task,args=('Python从入门到入院',)) #多线程
p1.start()
p2 = Process(target=download_task,args=('lookbook',))
p2 = Thread(target=download_task,args=('lookbook',))
p2.start()
p1.join()
p2.join()
end = time()
print('总共耗费%.2f秒'%(end - start))
if __name__ == "__main__":
main()
2.利用class类继承的方式调用多线程(Thread):
from random import randint
from time import time,sleep
from multiprocessing import Process #多进程
from os import getpid
from threading import Thread #多线程
class DownloadTask(Thread):
def __init__(self,filename):
super().__init__()
self.__filename = filename
def run(self):
print("开始下载%s......"%self.__filename)
time_to_download = randint(5,7)
sleep(time_to_download)
print('%s下载完成,总共用时%s'%(self.__filename,time_to_download))
def main():
start=time()
t1 = DownloadTask('Python从入门秘籍')
t1.start()
t2= DownloadTask('linweiwang')
t2.start()
t1.join()
t2.join()
end=time()
print('总共消耗%.2f秒'%(end - start))
if __name__ == "__main__":
main()
3.添加线程锁多线程执行数字的添加
from time import sleep
from threading import Thread,Lock
class Account(object):
def __init__(self):
self.__money=0
self.__lock=Lock() #加锁
def desopit(self,money):
self.__lock.acquire() #加锁令牌
try:
new_money=self.__money + money
sleep(0.1)
self.__money=new_money
finally:
self.__lock.release() #回收令牌
@property
def balance(self):
return self.__money
class AddmoneyThread(Thread):
def __init__(self,account,money):
super().__init__()
self.__account=account
self.__money=money
def run(self):
self.__account.desopit(self.__money)
def main():
account=Account()
threads=[]
for _ in range(100):
t = AddmoneyThread(account,1)
threads.append(t)
t.start()
for t in threads:
t.join()
print('%d'%account.balance)
if __name__ == '__main__':
main()