一、锁在多线程中的使用:线程互斥
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. FreeBSD--如何最有效率的安装软件

    Freebsd 下如何最有效率的安装软件 From <https://www.cnblogs.com/apexchu/p/4131821.html> FreeBSD的默认下载工具是fetc ...

  2. PHP开发搭建环境二:开发工具PhpStorm安装、激活以及配置

    关于php的开发工具很多,目前市面上最好用最强大的莫过于PhpStorm这款开发神器了,但是鉴于很多开发者朋友在网站上下载的PhpStorm开发工具不能用,或者使用起来很不方便,笔者把最好用的下载地址 ...

  3. json_encode 的小技巧

    做了一个 API 文档自动生成,解析的是每个 控制器类 的注释 json 数据,在做测试工具的时候,多层的 json 只有通过一个 textarea 把数据弄进去.如下图 怎么格式化 Json 数据并 ...

  4. 嵌入式Linux编译内核步骤 / 重点解决机器码问题 / 三星2451

    嵌入式系统更新内核 1. 前言 手里有一块Friendly ARM的MINI2451的板子,这周试着编译内核,然后更新一下这个板子的Linux内核,想要更新Linux Kernel 4.1版本,但是种 ...

  5. Python全栈day 03

    Python全栈day 03 一.运算符补充 in ,逻辑运算符,判断某字符或某字符串是否在一个大的字符串中,输出得到bool型数据. value = '我是中国人' v = '我' if v in ...

  6. C语言字符篇(一)字符串转换函数

      #include <stdlib.h>   double atof(const char *nptr);  将字符串转换成双精度浮点数 int atoi(const char *npt ...

  7. Git Pro Book

    目录 2nd Edition (2014) Switch to 1st Edition Download Ebook The entire Pro Git book, written by Scott ...

  8. viewpager 无网络的时候滑动异常

    不知道大家有没有遇到过这种情况,就是框架是viewpager+fragment的架构.然后呢,fragment里面是webview.一般情况下,当没有网的时候,webviwe会说什么找不到网页,然后很 ...

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

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

  10. 网易云深度剖析Kubernetes优化与实践

    欢迎访问网易云社区,了解更多网易技术产品运营经验. 10 月 15 日,聚焦 Kubernetes 中国行业应用与技术落地的首届中国 Kubernetes 用户大会(KEUC)在杭州成功举办.本次大会 ...