python多线程、多进程、协程笔记

import threading
import time
import multiprocessing
import asyncio


movie_list = ['斗破.avi', '复仇者联盟.mp4', '斗罗大陆.rmvb']
music_list = ['七里香.mp3', '美人鱼.mp3', 'xxx.obi']
movie_format = ['avi', 'mp4', 'rmvb']
music_format = ['mp3']


def play(playlist):
    for i in playlist:
        if i.split('.')[1] in movie_format:
            print('您现在正在收看:{}'.format(i))
            time.sleep(2)
        elif i.split('.')[1] in music_format:
            print('您现在正在收听:{}'.format(i))
            time.sleep(2)
        else:
            print('该文件格式不支持:{}'.format(i))
            time.sleep(2)


async def async_play(playlist):
    for i in playlist:
        if i.split('.')[1] in movie_format:
            print('您现在正在收看:{}'.format(i))
            await asyncio.sleep(2)
        elif i.split('.')[1] in music_format:
            print('您现在正在收听:{}'.format(i))
            await asyncio.sleep(2)
        else:
            print('该文件格式不支持:{}'.format(i))
            await asyncio.sleep(2)


class MyThread(threading.Thread):
    def __init__(self, playlist):
        super().__init__()
        self.playlist = playlist

    def run(self):
        play(self.playlist)


# 普通的多线程运行
def thread_run():
    t1 = threading.Thread(target=play, args=(movie_list, ))
    t2 = threading.Thread(target=play, args=(music_list, ))
    t1.start()
    t2.start()


# 重写多线程
def class_thread_run():
    t3 = MyThread(movie_list)
    t4 = MyThread(music_list)
    t3.start()
    t4.start()


# 多进程
def multi_run():
    t5 = multiprocessing.Process(target=play, args=(movie_list, ))
    t6 = multiprocessing.Process(target=play, args=(music_list, ))
    t5.start()
    t6.start()


# 协程
def loop_run():
    loop = asyncio.get_event_loop()
    task = [async_play(movie_list), async_play(music_list)]
    loop.run_until_complete(asyncio.wait(task))
    loop.close()


if __name__ == '__main__':
    # thread_run()
    # class_thread_run()
    # multi_run()
    loop_run()

由于python全局解释锁(Global Interpreter Lock)的存在,使得python的多线程并不能真正达到提高工作效率的目的,所以在日常工作中推荐使用多进程+协程的方式。

转载于:https://www.cnblogs.com/wu-guo-xing/p/11433361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值