当前位置: 代码迷 >> 综合 >> Python3 线程
  详细解决方案

Python3 线程

热度:79   发布时间:2024-03-09 08:12:00.0

Python3 多线程

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

  • _thread
  • threading(推荐使用)

 

_thread

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

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

参数说明:

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

实列:

import _thread
import timedef Times(threadName):count = 0while count < 5:count += 1time.sleep(4)print("%s:%s" %(threadName, time.ctime(time.time())))#创建两个线程
try:print("Error: 启动线程")_thread.start_new_thread(Times, ("Thread-1",))_thread.start_new_thread(Times, ("Thread-2",))
except:print("Error: 无法启动线程")while 1:pass

threading

threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法:

  • threading.currentThread(): 返回当前的线程变量。
  • threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
  • threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:

  • run(): 用以表示线程活动的方法。
  • start():启动线程活动。
  • join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
  • isAlive(): 返回线程是否活动的。
  • getName(): 返回线程名。
  • setName(): 设置线程名。

heading模块包含以下的类:

  • Thread: 基本线程类
  • Lock:互斥锁
  • RLock:可重入锁,使单一进程再次获得已持有的锁(递归锁)
  • Condition:条件锁,使得一个线程等待另一个线程满足特定条件,比如改变状态或某个值。
  • Semaphore:信号锁,为线程间共享的有限资源提供一个”计数器”,如果没有可用资源则会被阻塞。
  • Event:事件锁,任意数量的线程等待某个事件的发生,在该事件发生后所有线程被激活。
  • Timer:一种计时器
  • Barrier:Python3.2新增的“阻碍”类,必须达到指定数量的线程后才可以继续执行。

实列:

import threading
import timedef threadings(i):print("%s working" %i)def Thread():for i in range(5):t=threading.Thread(target=threadings,args=(i,))t.start()print(" wait %s" %i)t.join()Thread()