Python--多线程基础

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值