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的多線程並不能真正達到提升工做效率的目的,因此在平常工做中推薦使用多進程+協程的方式。python

相關文章
相關標籤/搜索