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

  • 相关阅读:
    CDOJ 1059 秋实大哥与小朋友 STL(set)+离散化+BIT区间更新单点查询
    hdu 1754 线段树 水题 单点更新 区间查询
    ZOJ 2301 离散化
    hdu 1166 线段树 区间求和 +单点更新 CD模板
    UVA 12299 线段树 ( 单点跟新 , 区间查询)
    TTTTTTTTTTTTT LA 2191 树状数组 稍修改
    TTTTTTTTTTT LA 4329 BIT模版
    POJ 1912 凸包
    对django模型中的objects的理解
    巨蟒python全栈开发django4:url反向解析图解&&模板渲染2
  • 原文地址:https://www.cnblogs.com/wu-guo-xing/p/11433361.html
Copyright © 2011-2022 走看看