一、锁在多线程中的使用:线程互斥
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是一种 ...
随机推荐
- FreeBSD--如何最有效率的安装软件
Freebsd 下如何最有效率的安装软件 From <https://www.cnblogs.com/apexchu/p/4131821.html> FreeBSD的默认下载工具是fetc ...
- 使用windows api安装windows服务程序(C#)
3个步骤: 1.安装器代码编写 2.安装器工具类编写 1)安装.启动服务) 2)卸载服务 3.windows服务程序编写(参考:多线程.方便扩展的Windows服务程序框架) 4.代码下载,在文末(注 ...
- php 文件操作和文件上传
文件操作 http://www.w3school.com.cn/php/php_file.asp http://www.w3school.com.cn/php/php_file_open.asp ht ...
- 小白对异步IO的理解
前言 看到越来越多的大佬都在使用python的异步IO,协程等概念来实现高效的IO处理过程,可是我对这些概念还不太懂,就学习了一下. 因为是初学者,在理解上有很多不到位的地方,如果有错误,还希望能够有 ...
- Codeforces146D 概率DP
Bag of mice The dragon and the princess are arguing about what to do on the New Year's Eve. The drag ...
- saltstack执行远程命令
目录 Remote Execution salt state salt state 系统 salt state 系统流程 Runner salt runner Orchestrate Runner S ...
- BZOJ 5004: 开锁魔法II
比较显然 #include<cstdio> #include<algorithm> #include<cstring> using namespace std; i ...
- 云计算之路-阿里云上:愚人节被阿里云OCS愚
今天是愚人节,而我们却被阿里云OCS愚,很多地方的缓存一直不过期,造成很多页面中的数据一直不更新.这篇博文将向您分享我们这两天遇到的OCS问题. 阿里云OCS(Open Cache Service)是 ...
- PJMEDIA之录音器的使用(capture sound to avi file)
为了熟悉pjmedia的相关函数以及使用方法,这里练习了官网上的一个录音器的例子. 核心函数: pj_status_t pjmedia_wav_writer_port_create ( pj_pool ...
- 《Cracking the Coding Interview》——第2章:链表——题目2
2014-03-18 02:24 题目:给定一个单链表,找出倒数第K个节点. 解法:让一个指针先走K步,然后俩指针一起走到尽头.当然也可以先走到尽头数出链表的长度,然后第二次少走K步.其实耗费的工夫是 ...