一、锁在多线程中的使用:线程互斥
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之多线程:线程互斥与线程同步的更多相关文章

  1. python开发进程:互斥锁(同步锁)&进程其他属性&进程间通信(queue)&生产者消费者模型

    一,互斥锁,同步锁 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 竞争带来的结果就是错乱,如何控制,就是加锁处理 part1:多个进程共享同一打印终 ...

  2. linux c编程:线程互斥二 线程死锁

    死锁就是不同的程序在运行时因为某种原因发生了阻塞,进而导致程序不能正常运行.阻塞程序的原因通常都是由于程序没有正确使用临界资源. 我们举个日常生活中的例子来比喻死锁.我们把马路上行驶的汽车比作运行着的 ...

  3. (day29) 进程互斥锁 + 线程

    目录 进程互斥锁 队列和堆栈 进程间通信(IPC) 生产者和消费者模型 线程 什么是线程 为什么使用线程 怎么开启线程 线程对象的属性 线程互斥锁 进程互斥锁 进程间数据不共享,但是共享同一套文件系统 ...

  4. python中多线程相关

    基础知识 进程:进程就是一个程序在一个数据集上的一次动态执行过程 数据集:程序执行过程中需要的资源 进程控制块:完成状态保存的单元 线程:线程是寄托在进程之上,为了提高系统的并发性 线程是进程的实体 ...

  5. JAVA多线程提高二:传统线程的互斥与同步&传统线程通信机制

    本文主要是回顾线程之间互斥和同步,以及线程之间通信,在最开始没有juc并发包情况下,如何实现的,也就是我们传统的方式如何来实现的,回顾知识是为了后面的提高作准备. 一.线程的互斥 为什么会有线程的互斥 ...

  6. Python并发编程04 /多线程、生产消费者模型、线程进程对比、线程的方法、线程join、守护线程、线程互斥锁

    Python并发编程04 /多线程.生产消费者模型.线程进程对比.线程的方法.线程join.守护线程.线程互斥锁 目录 Python并发编程04 /多线程.生产消费者模型.线程进程对比.线程的方法.线 ...

  7. Python多线程(2)——线程同步机制

    本文介绍Python中的线程同步对象,主要涉及 thread 和 threading 模块. threading 模块提供的线程同步原语包括:Lock.RLock.Condition.Event.Se ...

  8. python学习笔记-(十三)线程&多线程

    为了方便大家理解下面的知识,可以先看一篇文章:http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html 线程 1.什么是线程? ...

  9. Python 学习入门(22)—— 线程同步

    Python主要通过标准库中的threading包来实现多线程.在当今网络时代,每个服务器都会接收到大量的请求.服务器可以利用多线程的方式来处理这些请求,以提高对网络端口的读写效率.Python是一种 ...

随机推荐

  1. Laravel操作上传文件的方法

    1.获取上传的文件 $file=$request->file('file');2.获取上传文件的文件名(带后缀,如abc.png) $filename=$file->getClientOr ...

  2. POJ:1703-Find them, Catch them(并查集好题)(种类并查集)

    Find them, Catch them Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 49867 Accepted: 153 ...

  3. Echarts 解决饼图文字过长重叠的问题

    之前在网上查找了很多关于解决饼图文字描述过长导致重叠的问题,找了很多一直没有一个合适的解决方案,最后自己只能花时间研究echarts文档,功夫不负有心人,终于解决了文字重叠展示不全等问题. 废话不多说 ...

  4. ElasticSearch 环境安装

    1)官网安装教程: http://www.elasticsearch.org/guide/reference/setup/installation/   2)简单安装: http://log.medc ...

  5. spark练习--mysql的读取

    前面我们一直操作的是,通过一个文件来读取数据,这个里面不涉及数据相关的只是,今天我们来介绍一下spark操作中存放与读取 1.首先我们先介绍的是把数据存放进入mysql中,今天介绍的这个例子是我们前两 ...

  6. 2,Python常用库之二:Pandas

    Pandas是用于数据操纵和分析,建立在Numpy之上的.Pandas为Python带来了两种新的数据结构:Pandas Series和Pandas DataFrame,借助这两种数据结构,我们能够轻 ...

  7. MySQL之查询性能优化(三)

    MySQL查询优化器的局限性 MySQL的万能“嵌套循环”并不是对每种查询都是最优的.不过还好,MySQL查询优化只对少部分查询不适用,而且我们往往可以通过改写查询让MySQL高效地完成工作. 关联子 ...

  8. idea无法新建maven项目

    之前用的都是eclipse,自从4月底入职新公司后,接触到了idea. 然后自己的电脑上也安装了idea,不过一直都没用,直到昨天打算开起来使用一下. 之后就是想新建一个maven项目,发现死活也新建 ...

  9. Jsoncpp 编译

    1. linux下编译jsoncpp 从(http://jsoncpp.sourceforge.net/)下载源码包“jsoncpp-src-0.5.0.tar.gz”,解压后在其解压后目录中运行 $ ...

  10. 关于safaire下hash前面需要加/(正斜杠)

    就是我们1.1框架是根据hash跳转的,今天我2.0跳转到1.1,pc一直测下来都是好的, 然后发现手机上一直跳转有问题,然后排查了半小时左右才发现  hash前面需要加/ 分割. 例如:http:/ ...