当前位置:Gxlcms > Python > python开发之thread线程基础实例入门

python开发之thread线程基础实例入门

时间:2021-07-01 10:21:17 帮助过:26人阅读

本文实例讲述了python开发之thread线程基础。分享给大家供大家参考,具体如下:

说到线程,我们要知道啥是串行,啥是并行程序

举个例子:

串行程序,就是一个一个的执行程序

  1. #python threading
  2. import time
  3. '''
  4. 每一秒中,
输出:this is a demo! ''' def serial(): '''串行输出''' time.sleep(1) print('this is a demo!') def main(): for i in range(5): serial() if __name__ == '__main__': main()

运行结果如下:

  1. >>>
  2. this is a demo!
  3. this is a demo!
  4. this is a demo!
  5. this is a demo!
  6. this is a demo!
  7. >>>

并行程序,就是很多个程序在同一时间(宏观)一起执行

  1. #python threading
  2. import threading
  3. import time
  4. '''
  5. 并行执行,
输出:Good!Good!Good!Good!Good! ''' def parallel(): '''并行输出''' time.sleep(1) print('Good!') def main(): for i in range(5): t = threading.Thread(target=parallel) t.start() if __name__ == '__main__': main()

当然我们通过执行程序,可以知道,并行程序要比串行程序执行的要快....

我们也可以获取到当前的线程及个数:

  1. #python threading
  2. import threading
  3. import time
  4. '''
  5. 并行执行,
输出: [, , , , , <_MainThread(MainThread, started 3964)>, ] 存在的线程数 : 7 Good!Good!Good!Good!Good! ''' def parallel(): '''并行输出''' time.sleep(1) print('Good!') def main(): for i in range(5): t = threading.Thread(target=parallel) t.start() if __name__ == '__main__': main() print(threading.enumerate()) print('存在的线程数 : %d'%threading.active_count())

运行结果如下:

  1. >>>
  2. [<thread(sockthread, started="" daemon="" 15424)="">, <thread(thread-3, started="" 15840)="">, <thread(thread-1, started="" 10884)="">, <thread(thread-2, started="" 14512)="">, <thread(thread-4, started="" 13204)="">, <_MainThread(MainThread, started 12924)>, <thread(thread-5, started="" 15476)="">]
  3. 存在的线程数 : 7
  4. >>> Good!Good!Good!Good!Good!
  5. </thread(thread-5,></thread(thread-4,></thread(thread-2,></thread(thread-1,></thread(thread-3,></thread(sockthread,>

希望本文所述对大家Python程序设计有所帮助。

人气教程排行