PYTHON機器學習自學/自修 整理[00028] ~ PYTHON – 100天从新手到大师(13.进程和线程.md)
PYTHON機器學習自學/自修 整理[00028] ~ PYTHON – 100天从新手到大师(13.进程和线程.md)
01.多行程(multiprocess)
from multiprocessing import Process
from os import getpid
from random import randint
from time import time, sleep
def download_task(filename):
print('启动下载进程,进程号[%d].' % getpid())
print('开始下载%s...' % filename)
time_to_download = randint(5, 10)
sleep(time_to_download)
print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))
def main():
start = time()#運算時間計時
p1 = Process(target=download_task, args=('Python从入门到住院.pdf',))
p2 = Process(target=download_task, args=('Peking Hot.avi',))
#Process对象的start方法用来启动进程
p1.start()
p2.start()
#join方法表示等待进程执行结束
p1.join()
p2.join()
end = time()#運算時間計時
print('总共耗费了%.2f秒.' % (end - start))
if __name__ == '__main__':
main()
02.多 執行序/線程(multithread)-(基本範例)
from random import randint
from threading import Thread
from time import time, sleep
def download(filename):
print('开始下载%s...' % filename)
time_to_download = randint(5, 10)
sleep(time_to_download)
print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))
def main():
start = time()
t1 = Thread(target=download, args=('Python从入门到住院.pdf',))
t2 = Thread(target=download, args=('Peking Hot.avi',))
t1.start()
t2.start()
t1.join()
t2.join()
end = time()
print('总共耗费了%.3f秒' % (end - start))
if __name__ == '__main__':
main()
03.多 執行序/線程(multithread)-(建立繼承執行序的類別)
from random import randint
from threading import Thread
from time import time, sleep
class DownloadTask(Thread):
#建立繼承執行序的類別
def __init__(self, filename):
super().__init__()
self._filename = filename
def run(self):
print('开始下载%s...' % self._filename)
time_to_download = randint(5, 10)
sleep(time_to_download)
print('%s下载完成! 耗费了%d秒' % (self._filename, time_to_download))
def main():
start = time()
t1 = DownloadTask('Python从入门到住院.pdf')
t2 = DownloadTask('Peking Hot.avi')
t1.start()
t2.start()
t1.join()
t2.join()
end = time()
print('总共耗费了%.2f秒.' % (end - start))
if __name__ == '__main__':
main()
04.多 執行序/線程(multithread)-(執行序配合鎖功能達到共享變數存取)
from time import sleep
from threading import Thread, Lock
class Account(object):
def __init__(self):
self._balance = 0
self._lock = Lock()
def deposit(self, money):
# 先获取锁才能执行后续的代码
self._lock.acquire()
try:
new_balance = self._balance + money
sleep(0.01)
self._balance = new_balance
finally:
# 在finally中执行释放锁的操作保证正常异常锁都能释放
self._lock.release()
@property
def balance(self):
return self._balance
class AddMoneyThread(Thread):
def __init__(self, account, money):
super().__init__()
self._account = account
self._money = money
def run(self):
self._account.deposit(self._money)
def main():
account = Account()
threads = []
i=0
for _ in range(100):
i+=1;
t = AddMoneyThread(account, i)
threads.append(t)
t.start()
for t in threads:
t.join()
print('账户余额为: ¥%d元' % account.balance)
if __name__ == '__main__':
main()