zoukankan      html  css  js  c++  java
  • Python 学习笔记 多线程-threading

      1. 多线程使用示例
        import threading
        from time import sleep, ctime
        
        def func():
            print threading.current_thread().name, 'start'
            for i in range(10):
                print threading.current_thread().name, i
                sleep(1)
            print threading.current_thread().name, 'done'
        
        
        
        def main():
            print 'test start...', threading.current_thread().name
            threads = []
            for i in range(10):
                t = threading.Thread(target=func, args=())   # 创建线程
                threads.append(t)
        
            for i in range(10):
                print threads[i].name
                threads[i].start()                           # 启动线程
        
        
            for i in range(10):
                threads[i].join()                 # 等待线程结束
        
            print 'test done...', threading.current_thread().name
        
        if __name__=='__main__':
            main()

        输出示例(不看也罢):

        test start... MainThread
        Thread-1
        Thread-2
         Thread-1 start
         Thread-2 Thread-1 Thread-3
        0
        startThread-3 Thread-4
        start
        Thread-3 0Thread-5
         
        
        Thread-4Thread-2  Thread-5 0Thread-6
        start
        
        start
        Thread-5 Thread-4 0Thread-7
        0 
        
        Thread-6 start
        Thread-6 0
         Thread-7Thread-8
         start
        Thread-7 0
        Thread-8 startThread-9
        
        Thread-8 0
        Thread-9 start
         Thread-9 0
        Thread-10
        Thread-10 start
        Thread-10 0
        Thread-3 Thread-2 1
        1
        Thread-7 Thread-1 11
         Thread-8Thread-6 1
        
        Thread-4 1
         1
        Thread-5 1Thread-9 1Thread-10 1
        
        
        Thread-3 Thread-6 2Thread-7 Thread-4 Thread-2 
        2
        2
        2
        2
        Thread-1 2
        Thread-8 2
        Thread-9 2
         Thread-5 2
        Thread-10 2
        Thread-6 3
        Thread-2 3Thread-3Thread-4Thread-7
          3 3
         Thread-1 
        33Thread-5
         
        3
        Thread-8 3
        Thread-10 3Thread-9 3
        
        Thread-6 4
         Thread-9 4Thread-5 
        4
        Thread-2 4
         Thread-3Thread-1 4Thread-7 4Thread-8
         Thread-4 4
         
        4
         4Thread-10
         4
        Thread-1 5
         Thread-5 5
         Thread-4 5
        Thread-7 Thread-3 Thread-105 Thread-8 Thread-2 555
        
        
        
        Thread-6 55Thread-9 
        5
        
        Thread-9 Thread-2 Thread-5 Thread-10 Thread-6Thread-1 6666
        
         6 Thread-7Thread-3 6
         Thread-8 
        
         6
        
        Thread-4 666
        
        
        Thread-10 7
        Thread-6Thread-9 7Thread-1 7
         7
         Thread-3 Thread-8Thread-4 77
         Thread-5 7
        
        Thread-2 7
        Thread-7 
        7
         7
        Thread-10 8
        Thread-8 8
         Thread-9Thread-2  88
        
        Thread-1 8
        Thread-5 8
         Thread-7 8
        Thread-3 8
        Thread-4 8
         Thread-6 8
        Thread-10 9
         Thread-5 9Thread-8 9
        
        Thread-3Thread-7 9
         Thread-9Thread-2  99
        
         9
        Thread-1 9
        Thread-4 9
         Thread-6 9
        Thread-8 Thread-5 doneThread-10 donedone
         Thread-7 
        done
        Thread-9 done
        
         Thread-2 Thread-3 donedone
        
        Thread-1 done
        Thread-4 doneThread-6 done
        
        test done... MainThread
        输出示例
      2. threading模块中的函数使用示例
        # the function in the module threading
        import threading
        from time import sleep, ctime
        
        
        # active_count()   return the num of active thread
        # current_thread() return current thread object
        # enumerate()      return the list of active threads
        # settrace(func)   provide a func for all thread
        
        
        def func():
            print threading.current_thread().name, 'start'
            print 'in', threading.current_thread().name,threading.enumerate()
            sleep(5)
            print threading.current_thread().name, 'done'
        
        def main():
            print 'test start...', threading.current_thread().name
            threads = []
        
            print 'active threads num', threading.active_count()
            print 'active threads list', threading.enumerate()
        
            for i in range(10):
                t = threading.Thread(target=func, args=())
                threads.append(t)
                print 'creat thread', t.name
        
            print 'active threads num', threading.active_count()
            print 'active threads list', threading.enumerate()
        
            for i in range(10):
                threads[i].start()
                print threads[i].name, 'is started'
                print 'active threads num', threading.active_count()
                print 'active threads list', threading.enumerate()
        
            print '-----------------------'
            print 'active threads num', threading.active_count()
            print 'active threads list', threading.enumerate()
        
            for i in range(10):
                threads[i].join()
        
        
            print '-----------------------'
            print 'active threads num', threading.active_count()
            print 'active threads list', threading.enumerate()
            print 'test done...', threading.current_thread().name
        
        if __name__=='__main__':
            main()

        输出示例(谨慎操作,文件很乱):

        test start... MainThread
        active threads num 1
        active threads list [<_MainThread(MainThread, started 139754671793984)>]
        creat thread Thread-1
        creat thread Thread-2
        creat thread Thread-3
        creat thread Thread-4
        creat thread Thread-5
        creat thread Thread-6
        creat thread Thread-7
        creat thread Thread-8
        creat thread Thread-9
        creat thread Thread-10
        active threads num 1
        active threads list [<_MainThread(MainThread, started 139754671793984)>]
        Thread-1 Thread-1 is startedstart
        
        in Thread-1active threads num 2
        active threads list  [[<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>]
        <_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>]
        Thread-2 start
        in  Thread-2 Thread-2[<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-2, started 139754526975744)>]
         is started
        active threads num 3
        active threads list [<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-2, started 139754526975744)>]
        Thread-3 startThread-3 
        in Thread-3is started [
        <_MainThread(MainThread, started 139754671793984)>active threads num 4, <Thread(Thread-1, started 139754535368448)>
        , <Thread(Thread-3, started 139754518583040)>, active threads list [<Thread(Thread-2, started 139754526975744)>]
        <_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-2, started 139754526975744)>]
        Thread-4 startThread-4
        in  Thread-4is started [
        <_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-2, started 139754526975744)>, active threads num 5<Thread(Thread-4, started 139754510190336)>
        ]
        active threads list [<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-4, started 139754510190336)>]
        Thread-5 startThread-5
        in  Thread-5 [<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, is started<Thread(Thread-2, started 139754526975744)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        
        active threads num 6
        active threads list [<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        Thread-6 start
        in  Thread-6Thread-6 [ is started<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        
        active threads num 7
        active threads list [<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        Thread-7 startThread-7
        in Thread-7  [is started<_MainThread(MainThread, started 139754671793984)>, 
        <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>active threads num 8, <Thread(Thread-5, started 139754501797632)>]
        
        active threads list [<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        Thread-8 start
        in  Thread-8Thread-8 [ is started<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-8, started 139754133776128)>, 
        <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>active threads num 9, <Thread(Thread-7, started 139754142168832)>, 
        <Thread(Thread-4, started 139754510190336)>, active threads list [<Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        <_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-8, started 139754133776128)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        Thread-9 startThread-9
        in  Thread-9 [is started<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-8, started 139754133776128)>
        , <Thread(Thread-9, started 139754125383424)>active threads num 10, 
        <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, active threads list [<Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        <_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-8, started 139754133776128)>, <Thread(Thread-9, started 139754125383424)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        Thread-10 Thread-10 start
        in Thread-10is started [
        <_MainThread(MainThread, started 139754671793984)>active threads num 11, 
        <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-8, started 139754133776128)>active threads list , [<Thread(Thread-9, started 139754125383424)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, <Thread(Thread-10, started 139754116990720)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)><_MainThread(MainThread, started 139754671793984)>, , <Thread(Thread-5, started 139754501797632)>]
        <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-8, started 139754133776128)>, <Thread(Thread-9, started 139754125383424)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, <Thread(Thread-10, started 139754116990720)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        -----------------------
        active threads num 11
        active threads list [<_MainThread(MainThread, started 139754671793984)>, <Thread(Thread-1, started 139754535368448)>, <Thread(Thread-8, started 139754133776128)>, <Thread(Thread-9, started 139754125383424)>, <Thread(Thread-2, started 139754526975744)>, <Thread(Thread-6, started 139754493404928)>, <Thread(Thread-7, started 139754142168832)>, <Thread(Thread-10, started 139754116990720)>, <Thread(Thread-4, started 139754510190336)>, <Thread(Thread-3, started 139754518583040)>, <Thread(Thread-5, started 139754501797632)>]
        Thread-4 Thread-1 done
         Thread-7Thread-10 done
         Thread-5 doneThread-6
         Thread-2 Thread-9done
        done
         doneThread-3 Thread-8done 
         
        donedonedone
        
        
        -----------------------
        active threads num 1
        active threads list [<_MainThread(MainThread, started 139754671793984)>]
        test done... MainThread
        输出示例
      3. 多线程使用示例二
        import threading
        from time import ctime, sleep
        
        loops = (4, 2)
        
        
        class MyThread(threading.Thread):
            def __init__(self, func, args, name=''):
                threading.Thread.__init__(self)
                self.name = name
                self.func = func
                self.args = args
        
            def getResult(self):
                return self.res
        
            def run(self):
                print 'starting', self.name, 'at:', ctime()
                self.res = self.func(*self.args)
                print self.name, 'finished at:', ctime()
        
        
        
        def loop(nloop, nsec):
            print 'start loop', nloop, 'at', ctime()
            sleep(nsec)
            print 'loop', nloop, 'done at:', ctime()
        
        
        def main():
            print 'starting at:', ctime()
            threads = []
            nloops = range(len(loops))
        
            for i in nloops:
                t = MyThread(loop,(i, loops[i]), loop.__name__)
                threads.append(t)
        
        
            for i in nloops:
                threads[i].start()
        
            for i in nloops:
                threads[i].join()
        
            print 'all done at:', ctime()
        
        
        if __name__=='__main__':
            main()

        输出示例:

        starting at: Sat Oct  6 00:58:05 2018
        starting loop at: Sat Oct  6 00:58:05 2018
        start loop 0 at Sat Oct  6 00:58:05 2018
        starting loop at: Sat Oct  6 00:58:05 2018
        start loop 1 at Sat Oct  6 00:58:05 2018
        loop 1 done at: Sat Oct  6 00:58:07 2018
        loop finished at: Sat Oct  6 00:58:07 2018
        loop 0 done at: Sat Oct  6 00:58:09 2018
        loop finished at: Sat Oct  6 00:58:09 2018
        all done at: Sat Oct  6 00:58:09 2018
        输出示例
      4. 自定义Thread类 my_thread_module.py
        import threading
        from time import ctime, sleep
        
        
        class MyThread(threading.Thread):
            def __init__(self, func, args, name=''):
                threading.Thread.__init__(self)
                self.name = name
                self.func = func
                self.args = args
        
            def getResult(self):
                return self.res
        
            def run(self):
                print 'starting', self.name, 'at:', ctime()
                self.res = self.func(*self.args)
                print self.name, 'finished at:', ctime()
      5. 单线程和多线程的比较
        from my_thread_module import MyThread
        from time import ctime, sleep
        
        def fib(x):
            sleep(0.005)
            if x < 2: return 1
            return (fib(x-1) + fib(x-2))
        
        def fac(x):
            sleep(0.1)
            if x < 2: return 1
            return (x * fac(x-1))
        
        def sum(x):
            sleep(0.1)
            if x < 2: return 1
            return (x + sum(x-1))
        
        funcs = [fib, fac, sum]
        n = 12
        
        def main():
            nfuncs = range(len(funcs))
        
            print '***single thread***'
            for i in nfuncs:
                print 'starting', funcs[i].__name__, 'at:', ctime()
                print funcs[i](n)
                print funcs[i].__name__, 'finished at:', ctime()
        
            print '
        ***multiple threads***'
            threads = []
            for i in nfuncs:
                t = MyThread(funcs[i],(n,),funcs[i].__name__)
                threads.append(t)
        
            for i in nfuncs:
                threads[i].start()
        
            for i in nfuncs:
                threads[i].join()
                print threads[i].getResult()
        
            print 'all done'
        
        if __name__=='__main__':
            main()

        输出示例:单线程用时5秒,多线程2秒

        ***single thread***
        starting fib at: Sat Oct  6 01:40:07 2018
        233
        fib finished at: Sat Oct  6 01:40:09 2018
        starting fac at: Sat Oct  6 01:40:09 2018
        479001600
        fac finished at: Sat Oct  6 01:40:11 2018
        starting sum at: Sat Oct  6 01:40:11 2018
        78
        sum finished at: Sat Oct  6 01:40:12 2018
        
        ***multiple threads***
        starting fib at: Sat Oct  6 01:40:12 2018
         starting startingfac sum  at:at: Sat Oct  6 01:40:12 2018
         Sat Oct  6 01:40:12 2018
        sum finished at:fac finished at: Sat Oct  6 01:40:13 2018
         Sat Oct  6 01:40:13 2018
        fib finished at: Sat Oct  6 01:40:14 2018
        233
        479001600
        78
        all done
        输出示例
  • 相关阅读:
    使用java写一个小白计算器
    UVALive 6911 Double Swords (Set,贪心,求区间交集)
    UVALive 6910 Cutting Tree(并查集应用)
    Gym 101102C Bored Judge(set--结构体集合)
    有序链表和顺序表
    Gym 101102B The Little Match Girl(贪心+规律)
    UVALive 7070 The E-pang Palace(暴力)
    数据库系统实现 第二章 数据存储
    数据库系统实现 第一章 DBMS实现概述
    数据库系统实现 第六章 查询执行
  • 原文地址:https://www.cnblogs.com/PPWEI/p/9746314.html
Copyright © 2011-2022 走看看