Python之进程和线程(day~14)

多进程 通过 Process类创建

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()
    # 通过 Process类创建进程对象,
    # *args表示接收任意个参数,调用时,将实参打包成一个元组传入
    p1 = Process(target=download_task,args=('Python从入门到放弃.pdf',))
    p1.start()
    p2 = Process(target=download_task,args=('加勒比海盗.avi',))
    p2.start()
    p1.join()
    p2.join()
    end = time()
    print('总共耗时%.2f秒.' %(end-start))

if __name__ == '__main__':
    main()

多线程 通过thread实现

from random import randint
from threading import Thread
from time import time,sleep

def download_task(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_task,args=('Python从入门到放弃.pdf',))
    t1.start()
    t2 = Thread(target=download_task,args=('加勒比海盗.avi',))
    t2.start()
    t3 = Thread(target=download_task('汇华咨询.doc'))
    t3.start()
    t1.join()
    t2.join()
    t3.join()
    end = time()
    print('总共耗时%.2f秒.' % (end - start))

if __name__ == '__main__':
    main()

多线程 通过继承方式实现

from random import randint
from threading import Thread
from time import time,sleep

class Download_task(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 = Download_task('Python从入门到放弃.pdf')
    t1.start()
    t2 = Download_task('加勒比海盗.avi')
    t2.start()
    t1.join()
    t2.join()
    end = time()
    print('总共耗时%.2f秒.' % (end - start))

if __name__ == '__main__':
    main()

多线程加锁对临界资源进行访问

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
            # 模拟受理存款业务需要0.01秒的时间
            sleep(0.01)
            # 修改账户余额
            self._balance = new_balance
        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 = []
    # 创建100个存款的线程向同一个账户中存钱
    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()

使用多线程将耗时间的任务放到一个独立的线程中执行

import time
import tkinter
import tkinter.messagebox
from threading import Thread


def show_about():
    tkinter.messagebox.showinfo('关于', '作者: 王宽(v1.0)')


def main():
    class DownloadTaskHandler(Thread):
        def run(self):
            # 模拟下载任务需要花费5秒钟时间
            time.sleep(5)
            tkinter.messagebox.showinfo('提示', '下载完成!')
            button1.config(state=tkinter.NORMAL)

    def download():
        # 禁用下载按钮
        button1.config(state=tkinter.DISABLED)
        # 核心:通过daemon参数将线程设置为守护线程,主线程退出,子线程也必须跟着退出。
        DownloadTaskHandler(daemon=True).start()

    top = tkinter.Tk()
    top.title('单线程')
    top.geometry('200x150')
    top.wm_attributes('-topmost', True)

    panel = tkinter.Frame(top)
    button1 = tkinter.Button(panel, text='下载', command=download)
    button1.pack(side='left')
    button2 = tkinter.Button(panel, text='关于', command=show_about)
    button2.pack(side='right')
    panel.pack(side='bottom')

    tkinter.mainloop()


if __name__ == '__main__':
    main()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值