python中threading超线程用法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了python中threading超线程用法。分享给大家供大家参考。具体分析如下:

threading基于Java的线程模型设计。锁(Lock)和条件变量(Condition)在Java中是对象的基本行为(每一个对象都自带了锁和条件变量),而在Python中则是独立的对象。Python Thread提供了Java Thread的行为的子集;没有优先级、线程组,线程也不能被停止、暂停、恢复、中断。Java Thread中的部分被Python实现了的静态方法在threading中以模块方法的形式提供。

threading 模块提供的常用方法:

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

threading模块提供的类:

Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local.

Thread是线程类,与Java类似,有两种使用方法,直接传入要运行的方法或从Thread继承并覆盖run():

# encoding: UTF-8
import threading
# 方法1:将要执行的方法作为参数传给Thread的构造方法
def func():
  print 'func() passed to Thread'
t = threading.Thread(target=func)
t.start()
# 方法2:从Thread继承,并重写run()
class MyThread(threading.Thread):
  def run(self):
    print 'MyThread extended from Thread'
t = MyThread()
t.start()

构造方法:

Thread(group=None, target=None, name=None, args=(), kwargs={})
group: 线程组,目前还没有实现,库引用中提示必须是None;
target: 要执行的方法;
name: 线程名;
args/kwargs: 要传入方法的参数。

实例方法:

isAlive(): 返回线程是否在运行。正在运行指启动后、终止前。
get/setName(name): 获取/设置线程名。
is/setDaemon(bool): 获取/设置是否守护线程。初始值从创建该线程的线程继承。当没有非守护线程仍在运行时,程序将终止。
start(): 启动线程。
join([timeout]): 阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。

一个使用join()的例子:

# encoding: UTF-8
import threading
import time
def context(tJoin):
  print 'in threadContext.'
  tJoin.start()
  # 将阻塞tContext直到threadJoin终止。
  tJoin.join()
  # tJoin终止后继续执行。
  print 'out threadContext.'
def join():
  print 'in threadJoin.'
  time.sleep(1)
  print 'out threadJoin.'
tJoin = threading.Thread(target=join)
tContext = threading.Thread(target=context, args=(tJoin,))
tContext.start()

运行结果:

in threadContext.
in threadJoin.
out threadJoin.
out threadContext.

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

相关文章

如何使用Python实现自动化水军评论

如何使用Python实现自动化水军评论

前言 玩博客一个多月了,渐渐发现了一些有意思的事,经常会有人用同样的评论到处刷,不知道是为了加没什么用的积分,还是纯粹为了表达楼主好人。那么问题来了,这种无聊的事情当然最好能够自动化咯,...

Python3实现从文件中读取指定行的方法

本文实例讲述了Python3实现从文件中读取指定行的方法。分享给大家供大家参考。具体实现方法如下: # Python的标准库linecache模块非常适合这个任务 import li...

解决Python3下map函数的显示问题

map函数是Python里面比较重要的函数,设计灵感来自于函数式编程。Python官方文档中是这样解释map函数的: map(function, iterable, ...) Retu...

python脚本设置超时机制系统时间的方法

python脚本设置超时机制系统时间的方法

本文为大家介绍了python脚本设置系统时间的方法,一共有两种,其一是调用socket直接发送udp包到国家授时中心,其二是调用ntplib包。我在本地电脑ping 国家授时中心地址cn...

在Python的Django框架中使用通用视图的方法

使用通用视图的方法是在URLconf文件中创建配置字典,然后把这些字典作为URLconf元组的第三个成员。 例如,下面是一个呈现静态“关于”页面的URLconf: from djan...