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的多线程并不能真正达到提高工作效率的目的,所以在日常工作中推荐使用多进程+协程的方式。

上一篇:JVM钩子函数的使用


下一篇:Python网络爬虫笔记12:Scrapy进阶之数据建模与翻页