一、锁在多线程中的使用:线程互斥
lock = threading.Lock()#创建一个锁对象
1、with lock:
pass
和进程使用的方式相同
2、控制线程结束的时间
通过一个全局变量
# encoding=utf-8
import threading,time,Queue,random
exitFlag = False
def write(lock,queue):
while exitFlag != True:
with lock:
data = random.randint(1,100)
print 'put:',data
queue.put(data)
time.sleep(1)
def read(queue):
while exitFlag != True:
print 'get:',queue.get()
time.sleep(1)
if __name__ == '__main__':
lock = threading.Lock()
queue = Queue.Queue()
t1 = threading.Thread(target=write,args=(lock,queue))
t2 = threading.Thread(target=write,args=(lock,queue))
t3 = threading.Thread(target=read,args=(queue,))
t1.start()
t2.start()
t3.start()
time.sleep(10)
exitFlag = True
t1.join()
t2.join()
t3.join()
二、线程同步
1、生产者--消费者模式
Queue() 作为生产者和消费者的中介
from
class Producer(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self,name=t_name)#继承父类的构造方法的目的:初始化一些线程实例,
self.data=queue
def run(self):
for i in xrange(5):
print '%s:%s is producing %d to the queue\n'%(time.ctime(),self.getname(),i)
self.data.put(i)
time.sleep(2)
print '%s:%s put finished \n'%(time.ctime(),self.getname(),i)
def Consumer(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self,name=t_name)
self.data=queue
def run(self):
for i in xrange(5):
val=self.data.get()
print '%s:%s is consumer %d in the queue\n'%(time.ctime(),self.getname(),val)
print '%s:%s consumer finished \n'%(time.ctime(),self.getname(),i)
if __name=='__main__':
queue=Queue()#没有制定队列大小,默认为无限大,可以不受限制的放入队列
producer=Producer('Pro',queue)
consumer=Consumer('Con',queue)
producer.start()
time.sleep(1)
consumer.start()
producer.join()
consumer.join()
print 'mainThread end'
2、Event 信号传递
event=threading.Event()
import threading,time,Queue,random
def write(lock,queue,event):
while not event.isSet():
with lock:
thread = threading.currentThread()
data = random.randint(1,100)
print 'this is thread:',thread.getName(),'put:',data
queue.put(data)
time.sleep(1)
def read(queue):
while not event.isSet():
print 'get:',queue.get()
time.sleep(1)
if __name__ == '__main__':
lock = threading.Lock()
queue = Queue.Queue()
event=threading.Event()
t1 = threading.Thread(target=write,args=(lock,queue,event))
t2 = threading.Thread(target=write,args=(lock,queue,event))
t3 = threading.Thread(target=read,args=(queue,))
t1.start()
t2.start()
t3.start()
time.sleep(10)
event.set()
t1.join()
t2.join()
t3.join()
3、lock :只能加一把锁
4、semaphore:可以加多把锁
设置限制最多3个线程同时访问共享资源:s = threading.Semaphore(3)
5、event:线程等待某一时间的发生,之后执行逻辑
6、Condition 条件
con=threading.Condition()
使用场景:处理复杂的逻辑。基于锁来实现的
两个线程之间做一些精准的通信
线程A做了某一件事,中途需要停止
线程B做另外一件事情,线程B通知线程A
线程A继续
(1)额外提供了wait()方法和notify()方法,用于处理复杂的逻辑
(2)wait()释放锁,并且等待通知
(3)Notify()唤醒对方,可以继续下去。但是需要两个线程之间需要抢锁,谁抢到执行谁
通过(2)和(3),实现线程间的通信。
import threading
import time
product = 0
exitFlag = False
def consumer(con):
global product
while exitFlag != True:
with con:
print 'enter consummer thread'
if product == 0:
con.wait()
else:
print 'now consummer 1 product'
product -= 1
print 'after consummer, we have ',product,'product now'
time.sleep(2)
def producer(con):
global product
while exitFlag != True:
with con:
print 'enter producer thread'
product += 1
con.notify()
print 'after producer, we have ', product, 'product now'
time.sleep(2)
if __name__ == '__main__':
con = threading.Condition()
c1 = threading.Thread(target=consumer,args=(con,))
p1 = threading.Thread(target=producer, args=(con,))
c1.start()
p1.start()
time.sleep(6)
exitFlag = True
c1.join()
p1.join()
7、死锁
t1:拥有lock1锁,申请lock2锁
t2:拥有lock2锁,申请lock1锁
(1)如何尽量的保证不出现死锁:
定义锁的使用顺序
- python开发进程:互斥锁(同步锁)&进程其他属性&进程间通信(queue)&生产者消费者模型
一,互斥锁,同步锁 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 竞争带来的结果就是错乱,如何控制,就是加锁处理 part1:多个进程共享同一打印终 ...
- linux c编程:线程互斥二 线程死锁
死锁就是不同的程序在运行时因为某种原因发生了阻塞,进而导致程序不能正常运行.阻塞程序的原因通常都是由于程序没有正确使用临界资源. 我们举个日常生活中的例子来比喻死锁.我们把马路上行驶的汽车比作运行着的 ...
- (day29) 进程互斥锁 + 线程
目录 进程互斥锁 队列和堆栈 进程间通信(IPC) 生产者和消费者模型 线程 什么是线程 为什么使用线程 怎么开启线程 线程对象的属性 线程互斥锁 进程互斥锁 进程间数据不共享,但是共享同一套文件系统 ...
- python中多线程相关
基础知识 进程:进程就是一个程序在一个数据集上的一次动态执行过程 数据集:程序执行过程中需要的资源 进程控制块:完成状态保存的单元 线程:线程是寄托在进程之上,为了提高系统的并发性 线程是进程的实体 ...
- JAVA多线程提高二:传统线程的互斥与同步&传统线程通信机制
本文主要是回顾线程之间互斥和同步,以及线程之间通信,在最开始没有juc并发包情况下,如何实现的,也就是我们传统的方式如何来实现的,回顾知识是为了后面的提高作准备. 一.线程的互斥 为什么会有线程的互斥 ...
- Python并发编程04 /多线程、生产消费者模型、线程进程对比、线程的方法、线程join、守护线程、线程互斥锁
Python并发编程04 /多线程.生产消费者模型.线程进程对比.线程的方法.线程join.守护线程.线程互斥锁 目录 Python并发编程04 /多线程.生产消费者模型.线程进程对比.线程的方法.线 ...
- Python多线程(2)——线程同步机制
本文介绍Python中的线程同步对象,主要涉及 thread 和 threading 模块. threading 模块提供的线程同步原语包括:Lock.RLock.Condition.Event.Se ...
- python学习笔记-(十三)线程&多线程
为了方便大家理解下面的知识,可以先看一篇文章:http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html 线程 1.什么是线程? ...
- Python 学习入门(22)—— 线程同步
Python主要通过标准库中的threading包来实现多线程.在当今网络时代,每个服务器都会接收到大量的请求.服务器可以利用多线程的方式来处理这些请求,以提高对网络端口的读写效率.Python是一种 ...
随机推荐
- Linux Kernel ---- PCI Driver 分析
自己笔记使用. Kernel 版本 4.15.0 (ubuntu 18.04,intel skylake) 最近想学习VGA驱动去了解 DDCCP / EDID 等协议,然后顺便了解下驱动是如何工作的 ...
- OpenLDAP部署目录服务
文档信息 目 的:搭建一套完整的OpenLDAP系统,实现账号的统一管理. 1:OpenLDAP服务端的搭建 ...
- 【PHP基础】序列化serialize()与反序列化unserialize()
序列化serialize()与反序列化unserialize(): 序列化serialize():就是将一个变量所代表的 “内存数据”转换为“字符串”的形式,并持久保存在硬盘(写入文件中保存)上的一种 ...
- PHP 微信公众号真正正确的客服头像上传
首先我们来看官方文档 这TM的搞笑呢 什么破玩意儿! 需要条件 1 需要有一个客服的账号 (废话) 2 一致jpg格式的图片(扯蛋) 完整流程 1 获取access_token 2获取账号 3 $ur ...
- Codeforces Round 97B 点分治
B. Superset time limit per test 2 seconds memory limit per test 256 megabytes input standard input o ...
- Android 使用RxJava实现一个发布/订阅事件总线
1.简单介绍 1.1.发布/订阅事件主要用于网络请求的回调. 事件总线可以使Android各组件之间的通信变得简单,而且可以解耦. 其实RxJava实现事件总线和EventBus比较类似,他们都依据与 ...
- Web安全1&沙箱隔离
1.web安全 Web安全的本质是信任问题 •由于信任,正常处理用户恶意的输入导致问题的产生 •非预期的输入(就是不是程序员预期的客户的输入) 安全是木桶原理,短的那块板决定的木桶世纪能装多少水,同样 ...
- Xcode 代码提示功能失效
前言: 以前好像很少碰到Xcode中代码提示出问题的情况,最近经常遇到这个问题.没有了Xcode的智能提示,发现我已完全不会写代码了. 本来想吐槽下万恶的baidu,鉴于百度前端时间的各种(贴吧.竞价 ...
- Vbs 测试程序二
这是一段原载于百度百科上的代码,Chaobs转载 原帖已删,就是怕有人用这个恶意程序. 慎用! dim folder,fso,foldername,f,d,dc set fso=createobjec ...
- USACO Section1.3 Mixing Milk 解题报告
milk解题报告 —— icedream61 博客园(转载请注明出处)----------------------------------------------------------------- ...