Python多线程thread及模块使用实例

多线程类似于同时执行多个不同程序,多线程运行有如下优点:

  • 使用线程可以把占据长时间的程序中的任务放到后台去处理。
  • 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度
  • 程序的运行速度可能加快
  • 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等。

线程在执行过程中与进程还是有区别的。每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。

每个线程都有他自己的一组CPU寄存器,称为线程的上下文,该上下文反映了线程上次运行该线程的CPU寄存器的状态。

指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器,线程总是在进程得到上下文中运行的,这些地址都用于标志拥有线程的进程地址空间中的内存。

线程可以被抢占(中断)。

在其他线程正在运行时,线程可以暂时搁置(也称为睡眠) -- 这就是线程的退让。

线程可以分为:

内核线程:由操作系统内核创建和撤销。

用户线程:不需要内核支持而在用户程序中实现的线程。

Python3 线程中常用的两个模块为:

  • _thread
  • threading(推荐使用)

thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用"thread" 模块。为了兼容性,Python3

将 thread 重命名为 "_thread"。

Python中使用线程有两种方式:函数或者用类来包装线程对象。

函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:

_thread.start_new_thread ( function, args[, kwargs] )

参数说明:

  • function - 线程函数。
  • args - 传递给线程函数的参数,他必须是个tuple类型。
  • kwargs - 可选参数。
import _thread
from time import sleep
import datetime

def date_time_str():
  return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def loop_one():
  print('++++线程一开始于:',date_time_str())
  print('++++线程一休眠4秒')
  sleep(4)
  print('++++线程一休眠结束,结束于:',date_time_str())
      
def loop_two():
  print('++++线程二开始于:',date_time_str())
  print('++++线程二休眠2秒')
  sleep(2)
  print('++++线程二休眠结束,结束于:',date_time_str())
      
def main():
  print('-----所有线程开始时间:',date_time_str())
  _thread.start_new_thread(loop_one,())
  _thread.start_new_thread(loop_two,())
  sleep(6)
  print('------所有线程结束时间:',date_time_str())
      
if __name__=='__main__':
  main()

运行结果:

[python@master thread]$ python3 thread.py
-----所有线程开始时间: 2018-11-08 19:07:54
++++线程一开始于: 2018-11-08 19:07:54
++++线程一休眠4秒
++++线程二开始于: 2018-11-08 19:07:54
++++线程二休眠2秒
++++线程二休眠结束,结束于: 2018-11-08 19:07:56
++++线程一休眠结束,结束于: 2018-11-08 19:07:58
------所有线程结束时间: 2018-11-08 19:08:00

sleep(6) 是让主线程停下来,主线程一旦运行结束,就关闭运行着的其他两个线程,这可能造成主线程过早或者过晚退出,这时就要用线程锁,主线程可认在两个子进程都退出后立即退出。代码如下:

import _thread
from time import sleep
import datetime

loops=[4,2]

def date_time_str():
  return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def loop(n_loop,n_sec,lock):
  print('线程(',n_loop,') 开始执行:',date_time_str(),',先休眠(',n_sec,')秒')
  sleep(n_sec)
  print('线程(',n_loop,')休眠结束,结束于:',date_time_str())
  lock.release()
def main():
  print('---所有线程开始执行...')
  locks=[]
  n_loops=range(len(loops))
  for i in n_loops:
    lock=_thread.allocate_lock()
    lock.acquire()
    locks.append(lock)
  for i in n_loops:
    _thread.start_new_thread(loop,(i,loops[i],locks[i]))
  for i in n_loops:
    while locks[i].locked():
     pass
  print('---所有线程执行结束:',date_time_str())
  
if __name__=='__main__':
  main()

运行结果:

[python@master thread]$ python3 thread2.py
---所有线程开始执行...
线程( 1 ) 开始执行: 2018-11-08 20:00:47 ,先休眠( 2 )秒
线程( 0 ) 开始执行: 2018-11-08 20:00:47 ,先休眠( 4 )秒
线程( 1 )休眠结束,结束于: 2018-11-08 20:00:49
线程( 0 )休眠结束,结束于: 2018-11-08 20:00:51
---所有线程执行结束: 2018-11-08 20:00:51

使用了线程锁。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。