原文:http://www.pythonclub.org/python-basic/threading

一、python多线程thread和threading实现

python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的。

python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用。

这里需要提一下的是python对线程的支持还不够完善,不能利用多CPU,但是下个版本的python中已经考虑改进这点,让我们拭目以待吧。

threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class。

一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。

我们来看看这两种做法吧。

http://blog.csdn.net/guopengzhang/article/details/5458091

一)线程基础

1、创建线程:

thread模块提供了start_new_thread函数,用以创建线程。start_new_thread函数成功创建后还可以对其进行操作。

其函数原型:

start_new_thread(function,atgs[,kwargs])

其参数含义如下:

function: 在线程中执行的函数名

args:元组形式的参数列表。

kwargs: 可选参数,以字典的形式指定参数

方法一:通过使用thread模块中的函数创建新线程。

>>> import thread
>>> def run(n):
for i in range(n):
print i >>> thread.start_new_thread(run,(,)) #注意第二个参数一定要是元组的形式 >>> KeyboardInterrupt
>>> thread.start_new_thread(run,(,)) >>>
thread.start_new_thread(run,(),{'n':}) >>> thread.start_new_thread(run,(),{'n':}) >>>

方法二:通过继承threading.Thread创建线程

>>> import threading
>>> class mythread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num
def run(self): #重载run方法
print 'I am', self.num >>> t1 = mythread()
>>> t2 = mythread()
>>> t3 = mythread()
>>> t1.start() #运行线程t1
I am
>>>
t2.start()
I am
>>>
t3.start()
I am
>>>

方法三:使用threading.Thread直接在线程中运行函数。

import threading
>>> def run(x,y):
for i in range(x,y):
print i >>> t1 = threading.Thread(target=run,args=(,)) #直接使用Thread附加函数args为函数参数 >>> t1.start() >>>

二)Thread对象中的常用方法:

1、isAlive方法:

>>> import threading
>>> import time
>>> class mythread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
self.id = id
def run(self):
time.sleep() #休眠5秒
print self.id >>> t = mythread()
>>> def func():
t.start()
print t.isAlive() #打印线程状态 >>> func()
True
>>>

2、join方法:

原型:join([timeout])

timeout: 可选参数,线程运行的最长时间

import threading
>>> import time #导入time模块
>>> class Mythread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
self.id = id
def run(self):
x =
time.sleep()
print self.id >>> def func():
t.start()
for i in range():
print i >>> t = Mythread()
>>> func() >>>
def func():
t.start()
t.join()
for i in range():
print i >>> t = Mythread()
>>> func() >>>

3、线程名:

>>> import threading
>>> class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
print self.getName() >>>
>>> t1 = mythread('t1')
>>> t1.start()
t1
>>>

4、setDaemon方法

在脚本运行的过程中有一个主线程,如果主线程又创建了一个子线程,那么当主线程退出时,会检验子线程是否完成。如果子线程未完成,则主线程会在等待子线程完成后退出。

当需要主线程退出时,不管子线程是否完成都随主线程退出,则可以使用Thread对象的setDaemon方法来设置。

三)线程同步

1.简单的线程同步

使用Thread对象的Lock和RLock可以实现简单的线程同步。对于如果需要每次只有一个线程操作的数据,可以将操作过程放在acquire方法和release方法之间。如:

# -*- coding:utf- -*-
import threading
import time
class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x #设置全局变量
# lock.acquire() #调用lock的acquire方法
for i in range():
x = x +
time.sleep()
print x
# lock.release() #调用lock的release方法
#lock = threading.RLock() #生成Rlock对象
t1 = []
for i in range():
t = mythread(str(i))
t1.append(t)
x = #将全局变量的值设为0
for i in t1:
i.start() E:/study/python/workspace>xianchengtongbu.py

如果将lock.acquire()和lock.release(),lock = threading.Lock()删除后保存运行脚本,结果将是输出10个30。30是x的最终值,由于x是全局变量,每个线程对其操作后进入休眠状态,在线程休眠的时候,python解释器就执行了其他的线程而是x的值增加。当所有线程休眠结束后,x的值已被所有线修改为了30,因此输出全部为30。

2、使用条件变量保持线程同步。

Python的Condition对象提供了对复制线程同步的支持。使用Condition对象可以在某些事件触发后才处理数据。Condition对象除了具有acquire方法和release的方法外,还有wait方法、notify方法、notifyAll方法等用于条件处理。

# -*- coding:utf- -*-
import threading
class Producer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x
con.acquire()
if x == :
con.wait()
# pass
else:
for i in range():
x = x +
con.notify()
print x
con.release()
class Consumer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x
con.acquire()
if x == :
con.wait()
#pass
else:
for i in range():
x = x -
con.notify()
print x
con.release()
con = threading.Condition()
x =
p = Producer('Producer')
c = Consumer('Consumer')
p.start()
c.start()
p.join()
c.join()
print x E:/study/python/workspace>xianchengtongbu2.py

线程间通信:

Event对象用于线程间的相互通信。他提供了设置信号、清除信宏、等待等用于实现线程间的通信。

1、设置信号。Event对象使用了set()方法后,isSet()方法返回真。

2、清除信号。使用Event对象的clear()方法后,isSet()方法返回为假。

3、等待。当Event对象的内部信号标志为假时,则wait()方法一直等到其为真时才返回。还可以向wait传递参数,设定最长的等待时间。

# -*- coding:utf- -*-
import threading
class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global event
if event.isSet():
event.clear()
event.wait() #当event被标记时才返回
print self.getName()
else:
print self.getName()
event.set()
event = threading.Event()
event.set()
t1 = []
for i in range():
t = mythread(str(i))
t1.append(t)
for i in t1:
i.start()

最新文章

  1. appium如何获取conten-desc内容文本
  2. 浅谈JSON数据解析方法
  3. C#中字典集合HashTable、Dictionary、ConcurrentDictionary三者区别
  4. python wmi使用
  5. Android(Xamarin)之旅(二)
  6. 介绍 .NET Standard
  7. php base64编码和urlencode
  8. EasyTouch 3.1中文翻译
  9. 关于项目中遇到的NullPointerException异常时处理手段
  10. OracleApps Dropship 流程
  11. Qt学习之路(1)------Qt常用类用法说明
  12. .NET通用权限系统快速开发框架源代码
  13. Gradle学习之构建java与web项目
  14. Jmeter(一)_环境部署
  15. 【转】hibernate 延迟加载
  16. mysql 5.7 版本的安装
  17. fastjson解析List对象
  18. protobuffer php使用
  19. CCCallFunc和CCSequence
  20. C# 使用UDP组播实现局域网桌面共享

热门文章

  1. springmvc导出excel(POI)
  2. Fisherfaces 算法的具体实现源码
  3. C# Excel常用控件总结
  4. CSS规范(OOCSS SMACSS BEM)
  5. 697. Degree of an Array@python
  6. LeetCode(96) Unique Binary Search Trees
  7. chardet使用方法
  8. 出现Android.os.NetworkOnMainThreadException 错误
  9. 关于学习Mongodb的几篇文章
  10. shell脚本举例