python中的threading_python中threading的用法
threading提供了一个比thread模块更高层的API来提供线程的并发性。这些线程并发运行并共享内存。
下面来看threading模块的具体用法:
一、Thread的使用 目标函数可以实例化一个Thread对象,每个Thread对象代表着一个线程,可以通过start()方法,开始运行。
这里对使用多线程并发,和不适用多线程并发做了一个比较:
首先是不使用多线程的操作:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
#compare for multi threads
import time
def worker():
print "worker"
time.sleep(1)
return
if __name__== "__main__":
for iin xrange(5):
worker()
执行结果如下:
下面是使用多线程并发的操作:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
import threading
import time
def worker():
print "worker"
time.sleep(1)
return
for iin xrange(5):
t= threading.Thread(target=worker)
t.start()
可以明显看出使用了多线程并发的操作,花费时间要短的很多。
二、threading.activeCount()的使用,此方法返回当前进程中线程的个数。返回的个数中包含主线程。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python
#current's number of threads
import threading
import time
def worker():
print "test"
time.sleep(1)
for iin xrange(5):
t= threading.Thread(target=worker)
t.start()
print "current has %d threads" % (threading.activeCount()- 1)
三、threading.enumerate()的使用。此方法返回当前运行中的Thread对象列表。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python
#test the variable threading.enumerate()
import threading
import time
def worker():
print "test"
time.sleep(2)
threads= []
for iin xrange(5):
t= threading.Thread(target=worker)
threads.append(t)
t.start()
for itemin threading.enumerate():
print item
for itemin threads:
print item
四、threading.setDaemon()的使用。设置后台进程。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python
#create a daemon
import threading
import time
def worker():
time.sleep(3)
print "worker"
t=threading.Thread(target=worker)
t.setDaemon(True)
t.start()
print "haha"
可以看出worker()方法中的打印操作并没有显示出来,说明已经成为后台进程。
python线程 threading.Thread 条件变量 同步线程
在用python的threading.Thread编写多线程程序时,最简单的就是是用锁,为使线程之间保持同步,可以使用threading.Condition() 条件变量
思路:
1.分析哪一块空间需要多线程读写,抽象出一个共享空间类,对共享空间设置读方法(get)和写方法(set)
2.为使读线程和写线程同步,可以用threading.Condition()产生一个条件,同一个条件有wait()和notify()
notifyAll()方法,wait使线程自己进入block(阻塞)状态,一个线程的notify可以使同一个条件变量中block
的线程得到运行的机会。notifyAll通知所有被阻塞的线程进入runnable状态。
3.所有对共享空间操作的方法(read or write)都封闭在acquire()和release()中间
========以下实例简单明了==================
#coding=utf-8
#file name is maker.py
import threading
import random,time
class Maker(threading.Thread):
def __init__(self,threadName,shareObject):
threading.Thread.__init__(self,name=threadName)
self.shareObject=shareObject
def run(self):
for x in range(1,5):
time.sleep(random.randrange(1,4))
self.shareObject.set(x)
print "%s threading write %d" %(threading.currentThread().getName(),x)
=============================================================================
#coding=utf-8
#file name is user.py
import threading
import time,random
class User(threading.Thread):
def __init__(self,threadName,shareObject):
threading.Thread.__init__(self,name=threadName)
self.shareObject=shareObject
self.sum=0
def run(self):
for x in range(1,5):
time.sleep(random.randrange(1,4))
tempNum=self.shareObject.get()
print "%s threading read %d" %(threading.currentThread().getName(),tempNum)
self.sum=self.sum+tempNum
def display(self):
print "sum is %d" %(self.sum)
=============================================================================
#coding=utf-8
#file name is shareInt.py
import threading
import time,random
class ShareInt():
def __init__(self):
self.threadCondition=threading.Condition()
self.shareObject=[]
#所有对共享空间操作的方法(read or write)都封闭在acquire()和release()中间
def set(self,num):
self.threadCondition.acquire() # 在调用一个读或者写共享空间的方法时,需要先拿到一个基本锁
# 基本锁的获得采用竞争机制,无法判断哪个线程会先运行
# 不拿基本锁会出现运行时错误:cannot notify on un-aquired lock
if len(self.shareObject)!=0:
print "%s threading try write! But shareObject is full" %(threading.currentThread().getName())
self.threadCondition.wait() # 在条件满足的情况下,会block掉调用这个方法的线程
# 这里使用while语句更好,因为block在这个位置后,
# 当再次运行此线程的时候,会从头再一次检查条件。
self.shareObject.append(num)
self.threadCondition.notify() # 一定要先调用notify()方法,在release()释放基本锁
self.threadCondition.release() # 可以理解为"通知"被wait的线程进入runnable状态,然后在它获得锁后开始运行
# 最后一定要release()释放锁,否则会导致死锁
def get(self):
self.threadCondition.acquire()
if len(self.shareObject)==0:
print "%s threading try read! But shareObject is empty" %(threading.currentThread().getName())
self.threadCondition.wait()
tempNum=self.shareObject[0]
self.shareObject.remove(tempNum)
self.threadCondition.notify()
self.threadCondition.release()
return tempNum
==============================测试代码===============================
#coding=utf-8
#file name is Test.py
from user import User
from maker import Maker
from shareInt import ShareInt
shareObject=ShareInt()
user1=User("user1",shareObject)
maker1=Maker("maker1",shareObject)
user1.start()
maker1.start()
user1.join()
maker1.join()
user1.display()
print "main threading over!"
python中的threading_python中threading的用法相关推荐
- python中的threading_python中threading超线程用法实例分析
本文实例讲述了python中threading超线程用法.分享给大家供大家参考.具体分析如下: threading基于Java的线程模型设计.锁(Lock)和条件变量(Condition)在Java中 ...
- python的多线程threading_Python中多线程thread与threading的实现方法,pythonthreading
Python中多线程thread与threading的实现方法,pythonthreading 学过Python的人应该都知道,Python是支持多线程的,并且是native的线程.本文主要是通过th ...
- python中的threading_Python中Threading用法详解
Python的threading模块松散地基于Java的threading模块.但现在线程没有优先级,没有线程组,不能被销毁.停止.暂停.开始和打断. Java Thread类的静态方法,被移植成了模 ...
- python中的threading_python中的threading模块使用说明
这段时间使用python做串口的底层库,用到了多线程,对这部分做一下总结.实际用完了后再回过头去看python的官方帮助文档,感觉受益匪浅,把里面的自己觉得有用的一些关键点翻译出来,留待后续查验. t ...
- python中os.path.join()的循环用法_Python中.join()和os.path.join()两个函数的用法详解
Python中有.join()和os.path.join()两个函数,具体作用如下: . join(): 连接字符串数组.将字符串.元组.列表中的元素以指定的字符(分隔符)连接生成一个新的字符串 ...
- Python中yield和yield from的用法
yield 后面接的是 future 对象 调用方 委托生成器 yield from 直接给出循环后的结果 yield from 委托者和子生成器直接通信 yield from 直接处理stopIte ...
- python str byte编码_Python3中内置类型bytes和str用法及byte和string之间各种编码转换 问题...
Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分.文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示.Python 3不会以任意隐式的方式混用str ...
- python中split的用法取第二个分片_python中split()函数的用法
函数:split() Python中有split()和os.path.split()两个函数,具体作用如下: split():拆分字符串.通过指定分隔符对字符串进行切片,并返回分割后的字符串列表(li ...
- python中list[1啥意思_详解Python中list[::-1]的几种用法
本文主要介绍了Python中list[::-1]的几种用法,分享给大家,具体如下: s = "abcde" list的[]中有三个参数,用冒号分割 list[param1:para ...
- python中的os abort_Python os.abort()用法及代碼示例
Python中的OS模塊提供了與操作係統進行交互的功能.操作係統屬於Python的標準實用程序模塊.該模塊提供了使用依賴於操作係統的功能的便攜式方法. os.abort()Python中的方法用於生成 ...
最新文章
- 牛客网在线编程题之“换汽水”
- python最新功能_Python在2020的新增功能:第1部分
- 1.Docker的安装以及配置国内源
- Java框架体系架构的知识,轻松拿下offer
- Java8新特性总结 -7.新API和工具
- 图像处理随笔——soft-nms
- 微信公众号-自定义菜单的创建
- 时间状语:(现在完成时)/ 固定语句(现在完成时)/29主动表被动/23过去完成时:又 名 过去的过去;/过去将来时/(过去完成时)/25 过去完成时,固定搭配/26 时间状语 (将来完成时)
- XSS靶场(二)xss.haozi
- dojo基础:dojo/request
- STM32F103X hal RTThread rtc驱动支持日期保存
- 机电工程专业成功转行IT的真实经历
- Base64-encoded key bytes may only be specified for HMAC signatures.
- 阿里云镜像站repo文件
- iOS 高德地图(五)绘制点标记
- perl dbi mysql 参数_perl dbi mysql-值精度
-问答-阿里云开发者社区-阿里云
- 北宋三司若干问题研究
- 【打开方式问题解决】该文件没有与之关联的应用来执行该操作。请安装应用,若已经安装应用,请在“默认应用设置“页面中创建关联。
- Python 进行HTTP代理 多线程实现微信刷投票开发
- 深信服上网行为管理开启snmp_SANGFOR上网行为管理系统用户手册.pdf