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模块的更多相关文章

  1. python学习笔记(threading多线程)

    博主昨天优化了接口框架想着再添加些功能 想到对接口的性能压力测试 在工作过程中之前都是使用的工具 如:loadrunner.jmeter 想着这次准备用python实现对接口的性能压力测试 首先要实现 ...

  2. python学习笔记(threading接口性能压力测试)

    又是新的一周 延续上周的进度 关于多进程的学习 今天实践下 初步设计的接口性能压力测试代码如下: #!/usr/bin/env python # -*- coding: utf_8 -*- impor ...

  3. Python 学习笔记(6)--常用模块(2)

    一.下载安装 下载安装有两种方式: yum\pip\apt-get 或者源码 下载源码 解压源码 进入目录 编译源码 python setup.py build 安装源码 python setup.p ...

  4. python学习笔记之常用模块(第五天)

    参考老师的博客: 金角:http://www.cnblogs.com/alex3714/articles/5161349.html 银角:http://www.cnblogs.com/wupeiqi/ ...

  5. python学习笔记13(模块、包)

    在Python中有一个概念叫做模块(module),比如在Python中要调用sqrt函数,必须用import关键字引入math这个模块,下面就来了解一下Python中的模块. 模块文件以.py后缀结 ...

  6. Python学习笔记十_模块、第三方模块安装、模块导入

    一.模块.包 1.模块 模块实质上就是一个python文件.它是用来组织代码的,意思就是把python代码写到里面,文件名就是模块的名称,test.py test就是模块的名称 2.包 包,packa ...

  7. Python学习笔记:bisect模块实现二分搜索

    在Python中可以利用bisect模块来实现二分搜索,该模块包含函数只有几个: import bisect L = [1,3,4,5,5,5,8,10] x = 5 bisect.bisect_le ...

  8. python学习笔记——线程threading (二)重写run()方法和守护进程daemon()

    1 run()方法 1.1 单个线程 在threading.Thread()类中有run()方法. from time import ctime,sleep import threading # 定义 ...

  9. python学习笔记(六):常用模块

    一.模块.包 什么是模块? 模块实质上就是一个python文件,它是用来组织代码的,意思就是说把python代码写到里面,文件名就是模块的名称,test.py test就是模块名称. 什么是包? 包, ...

随机推荐

  1. git秘钥配置--转

    git是分布式的代码管理工具,远程的代码管理是基于ssh的,所以要使用远程的git则需要ssh的配置.github的ssh配置如下:一 .设置git的user name和email:$ git con ...

  2. jQuery使用示例详解

    [jquery引用字段] <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv ...

  3. 学习SQL的点点滴滴(二)删除临时表

    select into 创建的表属于临时表,判断是否存在的方法 select c_adno,c_con_no into #temp from tb_contract IF OBJECT_ID( 'te ...

  4. Dictionary<TKey, TValue> 类

    C# Dictionary<TKey, TValue> 类 Dictionary<TKey, TValue> 泛型类提供了从一组键到一组值的映射.字典中的每个添加项都由一个值及 ...

  5. [转载]iOS 归档操作 NSCoding

    最近一个项目需要保存到本地文件,想用plist,但是发现很多内容是自定义的,于是只能自己归档接档.不难,找了一篇范文大家保存一下,方便以后学习使用. 转自:http://mobile.51cto.co ...

  6. Bootstrap整体架构

    大多数Bootstrap的使用者都认为Bootstrap只是提供了CSS组件和JavaScript插件,其实CSS组件和JavaScript插件只是Bootstrap框架的表现形式而已,他们都是构建在 ...

  7. centos中rabbitmq的安装及php支持

    转自:http://www.phpac.com/741.html 1.安装rabbitmq-c库和codegen配件 wget https://github.com/alanxz/rabbitmq-c ...

  8. 浅谈可扩展性框架:MEF

    之前在使用Prism框架时接触到了可扩展性框架MEF(Managed Extensibility Framework),体验到MEF带来的极大的便利性与可扩展性. 此篇将编写一个可组合的应用程序,帮助 ...

  9. web中session与序列化的问题

    最近在写网上商城项目的时候学习了一个关于session的序列化问题,过来总结一下. 众所周知,session是服务器端的一种会话技术,只要session没有关闭,一个会话就会保持.这里先引出一个问题: ...

  10. Uart的Verilog建模

    开发工具:Quartus II 9.1: 仿真软件:Questa Sim 10.0c: 硬件平台:Terasic DE2-115(EP2C35F672C6): 外设:MAX3232: 3个工程文件:& ...