Python学习笔记- Python threading模块
Python threading模块
直接调用
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time def sayhi(num):
print("running on number:%s" % num)
time.sleep(3) if __name__ =='__main__': #生成两个线程实例
t1 = threading.Thread(target=sayhi,args=(1,))
t2 = threading .Thread(target = sayhi,args=(2,)) #启动两个线程
t1.start()
t2.start() #打印线程名
print(t1.getName())
print(t2.getName())
继承调用
import threading
import time
class MyThread(threading.Thread):
def __init__(self,num):
# super(Mythread,self).__init__(self)
threading.Thread.__init__(self)
self.num = num def run(self): print('running on number%s' %self.num)
time.sleep(3) if __name__ == '__main__': t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
批量处理多线程及等待
import threading
import time def sayhi(num): print('running on number%s' %num)
time.sleep(5) if __name__ == '__main__':
'''
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
'''
t_list=[] #用于存储实例
for i in range(100):
t = threading.Thread(target=sayhi,args =[i,] ) #循环创建实例
t.start()
t_list.append(t) #将创建的实力添加到列表
for i in t_list:#循环列表中的创建的实例
i.join() #在每个列表后面添加等待
print('##############main###############')
守护线程(Daemon)
import threading
import time def run(n):
print('--------runnig----------')
time.sleep(200)
print('--------done------------') def main(self):
for i in range(5):
t = threading.Thread(target=run,args=[i,])
t.start()
t.join()
print('start thread',t.getName())
m = threading.Thread(target=main,args=[])
m.setDaemon(True)#将主线程设置为Daemon线程,它退出时,其它子线程会同时退出,不管是否执行完任务
m.start()
print('-----main thread done-----')
线程锁(互斥锁Mutex)
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time
def addNum():
global num #在每个进程中都获得这个全局变量
print('----get num:%s' %num)
time.sleep(2)
lock.acquire()#修改数据前加锁
num-=1
lock.release()#修改后释放锁 num = 100
thread_list=[]
lock = threading.Lock() #生成全局锁
for i in range(100):
t=threading.Thread(target=addNum)
t.start()
thread_list.append(t) for t in thread_list:
t.join() #等待所有线程执行完毕 print('final Num:%s'%num)
递归锁(RLock)
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading,time def run1():
print("grab the first part data")
lock.acquire()
global num
num +=1
lock.release()
return num
def run2():
print("grab the second part data")
lock.acquire()
global num2
num2+=1
lock.release()
return num2
def run3():
lock.acquire()#加递归锁
res = run1() #调用run1方法
print('--------between run1 and run2-----')
res2 = run2()#调用run2方法
lock.release()#释放递归锁
print(res,res2) if __name__ == '__main__': num,num2 = 0,0 #初始化变量
lock = threading.RLock()#创建线程锁
for i in range(10):
t = threading.Thread(target=run3) #创建线程
t.start() while threading.active_count() != 1:#判断是否只剩一个线程
print(threading.active_count())
else:
print('----all threads done---')
print(num,num2)
Semaphore(信号量)
互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据.
# !/usr/bin/env python
# -*- coding:utf-8 -*- import threading,time def run(n):
semaphore.acquire()
time.sleep(1)
print("run the thread: %s\n" %n)
semaphore.release() if __name__ == '__main__': num= 0
semaphore = threading.BoundedSemaphore(3) #最多允许5个线程同时运行
for i in range(20):
t = threading.Thread(target=run,args=(i,))
t.start() while threading.active_count() != 1:
pass #print threading.active_count()
else:
print('----all threads done---')
print(num)
线程间同步和交互Event
An event is a simple synchronization object;
the event represents an internal flag, and threads
can wait for the flag to be set, or set or clear the flag themselves.
通过Event来实现两个或多个线程间的交互
Event = threading.Event()
even.wait()
event.set()
event.clear()
实例:
import threading,time
def light():
if not event.isSet():
event.set() #wait就不阻塞 #绿灯状态
count = 0
while True:
if count < 10:
print('\033[42;1m--green light on---\033[0m')
elif count <13:
print('\033[43;1m--yellow light on---\033[0m')
elif count <20:
if event.isSet():
event.clear()
print('\033[41;1m--red light on---\033[0m')
else:
count = 0
event.set() #打开绿灯
time.sleep(1)
count +=1
def car(n):
while 1:
time.sleep(1)
if event.isSet(): #绿灯
print("car [%s] is running.." % n)
else:
print("car [%s] is waiting for the red light.." %n)
event.wait()
if __name__ == '__main__':
event = threading.Event()
Light = threading.Thread(target=light)
Light.start()
for i in range(3):
t = threading.Thread(target=car,args=(i,))
t.start()
Python学习笔记- Python threading模块的更多相关文章
- python学习笔记(threading多线程)
博主昨天优化了接口框架想着再添加些功能 想到对接口的性能压力测试 在工作过程中之前都是使用的工具 如:loadrunner.jmeter 想着这次准备用python实现对接口的性能压力测试 首先要实现 ...
- python学习笔记(threading接口性能压力测试)
又是新的一周 延续上周的进度 关于多进程的学习 今天实践下 初步设计的接口性能压力测试代码如下: #!/usr/bin/env python # -*- coding: utf_8 -*- impor ...
- Python 学习笔记(6)--常用模块(2)
一.下载安装 下载安装有两种方式: yum\pip\apt-get 或者源码 下载源码 解压源码 进入目录 编译源码 python setup.py build 安装源码 python setup.p ...
- python学习笔记之常用模块(第五天)
参考老师的博客: 金角:http://www.cnblogs.com/alex3714/articles/5161349.html 银角:http://www.cnblogs.com/wupeiqi/ ...
- python学习笔记13(模块、包)
在Python中有一个概念叫做模块(module),比如在Python中要调用sqrt函数,必须用import关键字引入math这个模块,下面就来了解一下Python中的模块. 模块文件以.py后缀结 ...
- Python学习笔记十_模块、第三方模块安装、模块导入
一.模块.包 1.模块 模块实质上就是一个python文件.它是用来组织代码的,意思就是把python代码写到里面,文件名就是模块的名称,test.py test就是模块的名称 2.包 包,packa ...
- Python学习笔记:bisect模块实现二分搜索
在Python中可以利用bisect模块来实现二分搜索,该模块包含函数只有几个: import bisect L = [1,3,4,5,5,5,8,10] x = 5 bisect.bisect_le ...
- python学习笔记——线程threading (二)重写run()方法和守护进程daemon()
1 run()方法 1.1 单个线程 在threading.Thread()类中有run()方法. from time import ctime,sleep import threading # 定义 ...
- python学习笔记(六):常用模块
一.模块.包 什么是模块? 模块实质上就是一个python文件,它是用来组织代码的,意思就是说把python代码写到里面,文件名就是模块的名称,test.py test就是模块名称. 什么是包? 包, ...
随机推荐
- LAMP平台搭建菜鸟入门级实验
LAMP平台搭建(菜鸟入门级) mysql 安装: (1)二进制安装 二进制安装 ,执行解压配置即可.无须执行三布安装. (2)源码编译安装 安装准备工作: (1)查看系统配置:#uname -a/ ...
- < 独立项目 - 文本挖掘 > - 2016/11/13 第二更 - <Python环境准备>
< 独立项目 - 文本挖掘 > 项目立项的相关背景介绍,TODO方向. 一.Ubuntu环境配置 主机系统:Windows 7 SP1 64位操作系统 | i5-4210 CPU | ...
- 使用nodejs防止csurf攻击的方法
一.CSRF是什么? CSRF(Cross-site request forgery),中文名称:跨站请求伪造,也被称为:one click attack/session riding,缩写为:CSR ...
- C# using 三种使用方式
http://www.cnblogs.com/fashui/archive/2011/09/29/2195061.html 1.using指令. using 命名空间名字.例如: using Syst ...
- iOS 关于GCD中的队列
GCD中队列分类及获得方式 1.串行队列 dispatch_queue_t queue = dispatch_queue_create("队列名", DISPATCH_QUEUE ...
- CPS冥想 - 1 重新审视CPS
这篇文章是在阅读Eric Lippert大神的MSDN Blog文章时同步写成的,其中主要是各种翻译,同时还混杂自己阅读文章的笔记和感想. 原博文地址 http://blogs.msdn.com/b/ ...
- 解决Tomcat catalina.out 不断成长导致档案过大的问题
Tomcat的网站上的说法http://wiki.apache.org/tomcat/FAQ/Logging#Q6: System.out 和 System.err 都被打印到 catalina.ou ...
- (转)winform Form 淡入淡出效果
原文地址:http://blog.csdn.net/a237428367/article/details/5933565 using System.Runtime.InteropServices; p ...
- BackTrack 5 开启SSHD服务
BackTrack 5 开启SSHD服务 1 service ssh start 但启动后,仍然无法从远程连接,会有提示: 1 Read from socket failed: Connection ...
- Jmeter组件5. 逻辑控制
逻辑控制组件也有不少,但是用到的情况也不多,只打算举个While controller结合Regular Expression Extractor的例子 Condition,跳出循环的条件 如果放空, ...