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

yipeiwu_com6年前Python基础

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

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

举个例子:

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

#python threading
import time
'''
  每一秒中,输出: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()

运行结果如下:

>>> 
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
>>>

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

#python threading
import threading
import time
'''
  并行执行,输出: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()

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

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

#python threading
import threading
import time
'''
  并行执行,输出:
  [<Thread(Thread-2, started 3480)>, <Thread(Thread-1, started 660)>,
  <Thread(SockThread, started daemon 2920)>, <Thread(Thread-3, started 916)>,
  <Thread(Thread-4, started 3476)>, <_MainThread(MainThread, started 3964)>,
  <Thread(Thread-5, started 2060)>]
  存在的线程数 : 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())

运行结果如下:

>>> 
[<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)>]
存在的线程数 : 7
>>> Good!Good!Good!Good!Good!

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

相关文章

python Pygame的具体使用讲解

python Pygame的具体使用讲解

一、实验介绍 1.1 实验内容 在本节课中,我们将讲解Pygame的常用对象及其操作,包括图形、动画、文字、音频等,确保同学们对Pygame有一个基础的了解,同时为后续课程做好准备。 1...

Python实现matplotlib显示中文的方法详解

Python实现matplotlib显示中文的方法详解

本文实例讲述了Python实现matplotlib显示中文的方法。分享给大家供大家参考,具体如下: 【注意】 可能与本文主题无关,不过我还是想指出来:使用matplotlib库时,下面两...

对Python中9种生成新对象的方法总结

先定义一个类: class Point: def __init__(self, x, y): self.x = x self.y = y 下面我们使用9种方法来生...

快速排序的算法思想及Python版快速排序的实现示例

快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。 1.分治法的基本思想...

pandas创建新Dataframe并添加多行的实例

处理数据的时候,偶然遇到要把一个Dataframe中的某些行添加至一个空白的Dataframe中的问题。 最先想到的方法是创建Dataframe,从原有的Dataframe中逐行筛选出指...