###引入多线程
# _*_ coding:utf-8 _*_
"""
file:-01 不智能.py
date: 2018-07-上午6:20
author:ting
desc:
执行完一个才执行下一个任务,没有把cpu完全利用起来,程序执行效率低下
"""
from time import ctime,sleep
def music(a):
for i in range(2):
print 'I was listening to %s.%s' % (a,ctime())
sleep(1)
def movie(b):
for i in range(2):
print 'I was watching to %s.%s' % (b,ctime())
sleep(5)
music('下雨了')
movie('快把我哥带走')
print 'all over %s' % ctime()
# _*_ coding:utf-8 _*_
"""
file:-02 智能.py
date: 2018-07-上午6:20
author:ting
desc:
多个软件可以同时运行
"""
import threading
from time import ctime,sleep
def music(a):
for i in range(2):
print 'I was listening to %s.%s' % (a,ctime())
sleep(1)
def movie(b):
for i in range(2):
print 'I was watching to %s.%s' % (b,ctime())
sleep(5)
# music('下雨了')
# movie('快把我哥带走')
t1 = threading.Thread(target=music,args=('下雨了',))
t1.start()
t2 = threading.Thread(target=movie,args=('快把我哥带走',))
t2.start()
print 'all over %s' % ctime()
###多线程
# _*_ coding:utf-8 _*_
"""
file:-03.py
date: 2018-07-上午6:27
author:ting
desc:
创建多个线程
多线程能干什么:(生产者消费者问题:(经典))
1.一直生产 一直消费 中间有阀值 避免供求关系不平衡
2.线程安全问题,要是线程同时来,听谁的
3.锁:一种数据结构 队列:先进线出 栈:先进后出
生产者消费者的优点(为什么经典的设计模式)
1.解耦(让程序各模块之间的关联性降到最低)
假设生产者和消费者是两个类,如果让生产者直接调用消费者的某个方法,那么生产者对于消费者就会产生
依赖(也就是耦合),如果将来消费者的代码发生变换,可能会影响到生产者,而如果两者都依赖于某个缓冲区,
两者之间不直接依赖,耦合也就相应降低了.
生活中的例子:我们 邮筒 邮递员
举个例子,我们去邮局投递信件,如果不使用邮筒(也就是缓冲区),你必须得把信直接交给邮递员,有同学会说,
直接交给邮递员不是挺简单的嘛,其实不简单,你必须得认识邮递员,才能把信给他(光凭身上的制服,万一有人
假冒呢???),这就产成你和邮递员之间的依赖了(相当于生产者消费者强耦合),万一哪天邮递员换人了,你还
要重新认识一下(相当于消费者变化导致修改生产者代码),而邮筒相对来说比较固定,你依赖它的成本就比较低
(相当于和缓冲区之间的弱耦合)
2.支持并发
生产者消费者是两个独立的并发体,他们之间是用缓冲区作为桥梁连接,生产者之需要往缓冲区里丢数据,就
可以继续生产下一个数据,而消费者者只需要从缓冲区里拿数据即可,这样就不会因为彼此速度而发生阻塞.
接着上面的例子:如果我们不使用邮筒,我们就得在邮局等邮递员,直到他回来了,我们才能把信给他,这
期间我们啥也不能干(也就是产生阻塞),或者邮递员挨家挨户的问(产生论寻)
3.支持忙闲不均
如果制造数据的速度时快时慢,缓冲区的好处就体现出来了,当数据制造快的时候,
消费者来不及处理,未处理的数据可以暂时存在缓冲区中,等生产者的速度慢下来,消费者再慢慢处理
情人节信件太多了,邮递员一次处理不了,可以放在邮筒中,下次在来取
"""
from threading import Thread
def Foo(arg):
print arg
print 'before'
# 线程和函数建立关系
t1 = Thread(target=Foo,args=(1,))
t1.start()
print t1.getName()
t2 = Thread(target=Foo,args=(2,))
t2.start()
print t2.getName()
print 'after'
# _*_ coding:utf-8 _*_
"""
file:-04.py
date: 2018-07-上午6:47
author:ting
desc:
主线程执行完之后,还在等子线程执行完,程序才结束
"""
from threading import Thread
import time
def Foo(arg):
for item in range(10):
print item
time.sleep(1)
print 'before'
t1 = Thread(target=Foo,args=(1,))
t1.start()
print 'after'
# _*_ coding:utf-8 _*_
"""
file:-05.py
date: 2018-07-上午6:50
author:ting
desc:
主线程不等子线程,即子线程的执行与主线程无关
"""
from threading import Thread
import time
def Foo(arg):
for item in range(10):
print item
time.sleep(1)
print 'before'
t1 = Thread(target=Foo,args=(1,))
t1.setDaemon(True)
t1.start()
print 'after'
# 这行代码可以看到子线程在后台依然执行
time.sleep(5)
# _*_ coding:utf-8 _*_
"""
file:-06.py
date: 2018-07-上午7:06
author:ting
desc:
可以控制主线程等待子线程的时间
"""
from threading import Thread
import time
def Foo():
for item in range(10):
print item
time.sleep(1)
print 'before'
t1 = Thread(target=Foo)
t1.start()
# 主线程到join()就不往下执行了,直到子进程执行完
t1.join()
print 'after'
# _*_ coding:utf-8 _*_
"""
file:-07.py
date: 2018-07-上午7:16
author:ting
desc:
"""
from threading import Thread
import time
def Foo():
for item in range(10):
print item
time.sleep(1)
print 'before'
t1 = Thread(target=Foo)
t1.start()
# 5 代表主进程只等子进程5秒
t1.join(5)
print 'after'
# _*_ coding:utf-8 _*_
"""
file:线程安全问题.py
date: 2018-07-上午3:41
author:ting
desc:
线程会出现异常无法输出正确的结果
"""
import threading
import time
num = 0
def run(n):
time.sleep(1)
global num
num += 1
print '%s\n' % num
for i in range(1500):
t = threading.Thread(target=run,args=(i,))
t.start()
# _*_ coding:utf-8 _*_
"""
file:线程加锁.py
date: 2018-07-上午3:39
author:ting
desc:
给线程加锁使得输出结果正确
"""
import threading
import time
num = 0
def run(n):
time.sleep(1)
global num
lock.acquire()
num += 1
print '%s\n' % num
lock.release()
lock = threading.Lock()
for i in range(1500):
t = threading.Thread(target=run,args=(i,))
t.start()
###多线程在操作系统中的应用
# _*_ coding:utf-8 _*_
"""
file:-08.py
date: 2018-07-上午7:30
author:ting
desc:
操作系统,生产者与消费者
"""
import threading
import Queue
import time
def Producer(name,que):
que.put('baozi')
print '%s:MADE A baizi~~' % name
def Customers(name,que):
que.get('baozi')
print '%s:GOT A baozi~~' % name
# 创建队列
q = Queue.Queue()
p1 = threading.Thread(target=Producer,args=['cooker1',q])
p2 = threading.Thread(target=Producer,args=['cooker2',q])
p1.start()
p2.start()
c1 = threading.Thread(target=Customers,args=['lily',q])
c2 = threading.Thread(target=Customers,args=['lucy',q])
c1.start()
c2.start()
# _*_ coding:utf-8 _*_
"""
file:-09.py
date: 2018-07-上午7:30
author:ting
desc:
忙闲不均,随机处理
吃包子比做包子慢才会正确执行
"""
import threading
import Queue
import time
import random
def Producer(name,que):
while True:
que.put('baozi')
print '%s:MADE A baizi~~' % name
time.sleep(random.randrange(5))
def Customers(name,que):
while True:
que.get('baozi')
print '%s:GOT A baozi~~' % name
time.sleep(random.randrange(2))
# 创建队列
q = Queue.Queue()
p1 = threading.Thread(target=Producer,args=['cooker1',q])
p2 = threading.Thread(target=Producer,args=['cooker2',q])
p1.start()
p2.start()
c1 = threading.Thread(target=Customers,args=['lily',q])
c2 = threading.Thread(target=Customers,args=['lucy',q])
c1.start()
c2.start()
# 程序一直在执行,不会停止
# _*_ coding:utf-8 _*_
"""
file:-10.py
date: 2018-07-上午7:58
author:ting
desc:
没有包子,就会提示顾客没有包子,不会傻傻的等
"""
import threading
import Queue
import time
import random
def Producer(name,que):
while True:
que.put('baozi')
print '%s:MADE A baizi~~' % name
time.sleep(random.randrange(5))
def Customers(name,que):
while True:
que.get('baozi')
print '%s:GOT A baozi~~' % name
print '没有包子了~~'
time.sleep(random.randrange(2))
# 创建队列
q = Queue.Queue()
p1 = threading.Thread(target=Producer,args=['cooker1',q])
p2 = threading.Thread(target=Producer,args=['cooker2',q])
p1.start()
p2.start()
c1 = threading.Thread(target=Customers,args=['lily',q])
c2 = threading.Thread(target=Customers,args=['lucy',q])
c1.start()
c2.start()
# 顾客来买包子时,如果没有,会提示没有包子,但厨师会一直在做包子(程序会一直运行)
# _*_ coding:utf-8 _*_
"""
file:-11.py
date: 2018-07-上午8:01
author:ting
desc:
"""
import threading
import Queue
import time
import random
def Producer(name,que):
while True:
if que.qsize() < 3:
que.put('baozi')
print '%s:MADE A baizi~~' % name
else:
print '还有三个包子~~'
time.sleep(random.randrange(5))
def Customers(name,que):
while True:
try:
que.get_nowait()
print '%s:GOT A baozi~~' % name
except Exception:
print '没有包子了~~'
time.sleep(random.randrange(1))
# 创建队列
q = Queue.Queue()
p1 = threading.Thread(target=Producer,args=['cooker1',q])
p2 = threading.Thread(target=Producer,args=['cooker2',q])
p1.start()
p2.start()
c1 = threading.Thread(target=Customers,args=['lily',q])
c2 = threading.Thread(target=Customers,args=['lucy',q])
c1.start()
c2.start()
# _*_ coding:utf-8 _*_
"""
file:事件驱动.py
date: 2018-07-上午3:29
author:ting
desc:
"""
import threading
import time
def Producer():
print 'chef:等人来买包子'
# 收到了消费者的event.set 也就是把这个flag改为了true,但是我们的包子并没有做好
event.wait()
# 此时应该将flag的值改回去
event.clear()
print 'chef:someone is coming for 包子'
print 'chef:making a 包子 for someone'
time.sleep(5)
# 告诉人家包子做好了
print '您的包子好了~'
event.set()
def Customer():
print 'lucy:去买包子'
# 告诉人家我来了
event.set()
time.sleep(2)
print 'lucy:waiting for 包子 to be ready'
event.wait()
print '哎呀~真好吃'
event = threading.Event()
p1 = threading.Thread(target=Producer)
c1 = threading.Thread(target=Customer)
p1.start()
c1.start()
# _*_ coding:utf-8 _*_
"""
file:异步.py
date: 2018-07-上午2:59
author:ting
desc:
"""
import threading
import time
def Producer():
print 'chef:等人来买包子'
# 收到了消费者的event.set,也就是把这个flag改为了true,但是我们的包子并没有做好
event.wait()
# 此时应该将flag改回去
event.clear()
print 'chef:someone is coming for 包子'
print 'chef:making a 包子 for someone'
time.sleep(5)
# 告诉人家包子做好了
print '您的包子好了~~'
event.set()
def Customer():
print 'lily:去买包子'
# 告诉人家我来了
event.set()
time.sleep(2)
print 'lily:wait for 包子 to be ready'
# 我不断检测,但我已经不阻塞了
while True:
if event.is_set():
print 'Thanks~~'
break
else:
print '怎么还没好呀~~'
# 模拟正在做自己的事情
time.sleep(1)
event = threading.Event()
p1 = threading.Thread(target=Producer)
c1 = threading.Thread(target=Customer)
p1.start()
c1.start()